How to fire a keypress event in code

kutz

Newcomer
Joined
Jan 30, 2005
Messages
4
Greetings,

As indicated in the title I am trying to work out how to raise a keypress event in code, something I cannot find an article or tutorial on anywhere!!

Which, to me, would be counter-inuitive as it would seem to be incredibly simple.

Any help would be greatly appreciated.

Regards,
Kutz
 
Are you trying to raise an event in your own control? Are you trying to cause another control to raise a keypress event? Are you just trying to call a keypress handler function? What exactly are you trying to do?
 
//C# code
// KeyPressEventArgs accepts a char as the input

private void Form1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
// do something based on the key pressed
}

private void button1_Click(object sender, System.EventArgs e)
{
char ch = 'a';
Form1_KeyPress(new object(),new System.Windows.Forms.KeyPressEventArgs(ch) );
}


OR

the other way would be to use keybd_event winapi
 
Cheers gents for your replies so far. I'm fine with standard keypress event handling.

What I am trying to do is simulate a key being pressed within a particular control. (In this case, a DateTimePicker) So the idea being that without the user touching a key, the program acts as if a user hit the 'enter' key while that control is focussed.

The trigger for this is clicking a button on the form.

Thanks for your help.
 
This will fire/raise the KeyPressEvent simulating the Enter key being pressed.
Code:
private void FakeEnterKeyPress()
{
    KeyPressEventArgs e= new KeyPressEventArgs(Convert.ToChar(13));
    OnKeyPress(e);
}
 
Last edited:
Back
Top