Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I check if a key is pressed? 1

Status
Not open for further replies.

RobCozzens

Programmer
Aug 20, 2003
5
US
I want to see if certain keys are pressed so I can scroll a window if the user is holding down the space bar.
Windows.Forms.Control has the static property ModifierKeys, but that only works for SHIFT, CTRL, and ALT. I need something that works the same way for any key.
 
because of the way a keyboard works, you can't really look at a key and ask it if it is down of up, you can only listen for the presses. what i had to do once (albeit in java, so i'm not providing sample code) wheni i wanted to know what was pressed is this:

1) i created an array of bools, large enough for each keycode to be covered.

2) i initialised every element to false

3) i listened to the key board. when a key went down i changed the apropriate element to true, when a key went up i changed it to false. in java i use KeyListener, but i think you should use the key up and down events in the windows.form (the EventArgs holds the answer to what key has been pressed).

4) when i want to check the state of a key, i take a look at my array.
 
Thanks.
Is there an easy way to have the top level form receive all the KeyUp and KeyDown events when a child control has focus?
 
any form you can reach through a parent-to-parent path from your control form can listen for events, you just need to make sure the form that is listening has unbroken access. by this i mean all the objects that are parents of the controlfor, and children of your top level form should contrin some kind of link to its apropriate child.

the easiest way to do this is to use properties. i'll try and explain with an example.

1) child form: this triggers events such as KeyUp and KeyDown.

2) direct parent of child: an instance of our child appears in here. make it publicly available through a property thus:

public Form child{ //don't write form, be more precise as to avoid casting later.
get{
return myForm; //'myForm' is the control form
}set{
myForm = value;
}
}


3) the top level object: the direct parent of child, is a child of this object. you can use the property to see your form through it, then listen for the event:

myChild.child.KeyUp += new System.EventHandler(someMethod);

good?

If you like a post, show you care by giving it a star.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top