Click here to Skip to main content
15,897,226 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I don't know if these two example work. I've been doing some research for a school project. I want to call a method that does something (for example adds text to textBox1.. ) when the key is pressed/down (without the need of hitting enter.) I want it to be very simple, yet I don't understand how to trigger them and if they are written correctly. Any attempt to help is very appreciated. Thank you.

C#
//Keypress:
private void myControl_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.a)
{
// call method?
}
}

//Keydown:
 private void Grid1_KeyDown(object sender, KeyEventArgs e)
        {
                if (e.KeyCode == Keys.a)
                {
                  //call method?
                }
        }
Posted

Bear in mind that they will only trigger when you control has the focus: I assume you have set these as the handler for the event, either in the control Properties window of the designer, or by manually adding them in the form Load event?

Start simply for testing:

Create a new form and handle the KeyPress, KeyUp and KeyDown events. In each of them, add a Console.WriteLine statement that identifies which you are in. (when you run you program, you can see this output in the Output pane at teh bottom of the screen.

Play with the code, until you are sure what is happening, and then transfer the code to the controls you are really interested in - just remember the focus!
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 10-Feb-11 10:58am    
Adequate explanation, 5,
--SA
Hi,

For example if you are using a text box your first method is correct. Just need to add the event handler in the form load

this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox1_KeyPress);

You can do this for all the controls which supports keypress event
 
Share this answer
 
You can always use the SendKeys method [^]to trigger keyboard events of your own.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900