put a break point in your key down event and press your two keys together. Show activity on this post.
How does a user generate multiple keydown events? Explanation: If the user holds the key down long enough for it to begin repeating, there will be multiple keydown events before the keyup event arrives. Pressing the key for long time results in multiple calls to the function onkeypress.
Both are used as per the need of your program and as per the convenience of the user. keyup Fires when the user releases a key, after the default action of that key has been performed. keydown Fires when the user depresses a key.
The keydown event is fired when a key is pressed. Unlike the keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.
You can check the modifiers of the KeyEventArgs like so:
private void listView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up && e.Modifiers == Keys.Control)
{
//do stuff
}
}
MSDN reference
From the MSDN page on KeyEventArgs:
if (e.KeyCode == Keys.F1 && (e.Alt || e.Control || e.Shift))
{
//Do stuff...
}
You can try using the Keyboard
object to detect the IsKeyDown
property. Also, if you don't want the browser shortcut to over-ride you can set Handled
property to true.But be careful when over-riding browser shortcuts as it could cause confusion.
private void Page_KeyDown(object sender, KeyEventArgs e)
{
// If leftCtrl + T is pressed autofill username
if (Keyboard.IsKeyDown(Key.T) && Keyboard.IsKeyDown(Key.LeftCtrl))
{
txtUser.Text = "My AutoFilled UserName";
e.Handled = true;
}
}
In the KeyEventArgs
there are properties Ctrl, Alt and Shift that shows if these buttons are pressed.
private void listView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Up && Keyboard.IsKeyDown(Key.LeftCtrl))
{
//do stuff
}
}
This code will work only if you press first LeftCtrl, then "UP". If order has no importance, I recommend that one :
if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))&& Keyboard.IsKeyDown(Key.Z))
{
//do stuff
}
In that case, both Ctrl are taken in account, and no importance about the order.
You can use the ModifierKeys property:
if (e.KeyCode == Keys.Up && (ModifierKeys & Keys.Control) == Keys.Control)
{
// CTRL + UP was pressed
}
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:
if (e.KeyCode == Keys.Up && ModifierKeys == Keys.Control)
{
// CTRL + UP was pressed
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With