I am not a WinForm programmer anymore but that does not stop me from trying out code when a user asks me a question about it.
I recently got a request where the user wanted to detect Ctrl and Shift keys on his windows form. The keys to be detected were Ctrl+C, Ctrl+V and Ctrl+Shift+C
Here’s how the keys can be detected:
C#
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if ((e.Control & e.Shift) && e.KeyCode == Keys.C)
{
MessageBox.Show("Ctrl+Shift+C");
}
else if (e.Control && e.KeyCode == Keys.C)
{
MessageBox.Show("Ctrl+C detected");
}
else if (e.Control && e.KeyCode == Keys.V)
{
MessageBox.Show("Ctrl+V detected");
}
}
VB.NET
Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs)I have seen users using the KeyPress event to solve this requirement. Remember that non-characters keys like Ctrl do not raise the KeyPress event. I prefer either the KeyUp or KeyDown instead.
If (e.Control And e.Shift) AndAlso e.KeyCode = Keys.C Then
MessageBox.Show("Ctrl+Shift+C")
ElseIf e.Control AndAlso e.KeyCode = Keys.C Then
MessageBox.Show("Ctrl+C detected")
ElseIf e.Control AndAlso e.KeyCode = Keys.V Then
MessageBox.Show("Ctrl+V detected")
End If
End Sub
Tweet
2 comments:
This is almost useless since this works if and only if focus is on Form1 and not any of it's controls.
thats not true Anonymous, it works if any control is focus, just add to "Load Event"
KeyPreview=true
Post a Comment