Friday, February 6, 2009

Key Hold "Hold CTRL then press ENTER"?

How to detect "Hold CTRL then press ENTER"?

1. KeyDown event:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
MessageBox.Show("e.KeyData:" + e.KeyData.ToString() +
"-e.KeyCode:" + e.KeyCode.ToString() + "-e.Modifiers:" +
e.Modifiers.ToString() + "-e.KeyValue:" + e.KeyValue.ToString());
if (e.KeyData == (Keys.Control | Keys.Enter))
MessageBox.Show("Ctrl+Enter!");
}

2. KeyPress event:

Modifierkeys are translated to characters
inside the KeyPress event. When you hold ctrl while clicking Enter
(char)10 is sent instead of (char)13 and the Control click is suppressed,
so all you have to do to detect Ctrl+Enter is

if(e.KeyChar == (char)10)

The same goes for other combinations like

if(e.KeyChar == (char)97) // [A]

if(e.KeyChar == (char)1 ) // [CTRL]+[A]

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
string s = e.KeyChar.ToString();
MessageBox.Show("e.KeyChar:" + s);
}

No comments: