Thursday, August 21, 2008

How to detect key press like:Ctrl + Enter

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!");
}


Note:

You can check for Ctrl inside the KeyPress event by using the static
properties Control.ModifierKeys
In theory you should be able to do

if(e.KeyChar == (char)13 && Control.ModifierKeys == Keys.Ctrl)

Except this doesn't work. 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]

To detect key combinations put something like this inside the KeyPress
event

MessageBox.Show(((int)e.KeyChar).ToString());

But to detect, you have to use

if (e.KeyData == (Keys.Control | Keys.Enter))

No comments: