How can I determine in KeyDown
that CtrlUp was pressed.
private void listView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Control && e.KeyCode == Keys.Up)
{
//do stuff
}
}
can't work, because never both keys are pressed exactly in the same second. You always to at first the Ctrl and then the other one...
In the
KeyEventArgs
there are properties Ctrl, Alt and Shift that shows if these buttons are pressed.this will work for sure. Be careful to handle
KeyUp
event and notkeyDown
.For me,
keyDown
didn't work,keyU
p worked instead for the same code.I don't know why, but it seems because
keyDown
event happens directly after you press any key, even if that was ctrl key, so if you pressed ctrl+Up you will press ctrl key before the UP key and thus the event will occur before you can press the other, also pressing the second key will triggers the event again.While using
KeyUp
will not trigger the event until you release the key, so you can press ctrl, and the press the second key, which will trigger one event.You can use the ModifierKeys property:
Note that the ModifierKeys value can be a combination of values, so if you want to detect that CTRL was pressed regardless of the state of the SHIFT or ALT keys, you will need to perform a bitwise comparison as in my sample above. If you want to ensure that no other modifiers were pressed, you should instead check for equality:
You can check the modifiers of the KeyEventArgs like so:
MSDN reference
From the MSDN page on KeyEventArgs:
You can try using the
Keyboard
object to detect theIsKeyDown
property. Also, if you don't want the browser shortcut to over-ride you can setHandled
property to true.But be careful when over-riding browser shortcuts as it could cause confusion.