Detecting Ctrl and Shift Keys on a Form using C# or VB.NET

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)
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
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.

Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

2 comments:

Anonymous said...

This is almost useless since this works if and only if focus is on Form1 and not any of it's controls.

Anonymous said...

thats not true Anonymous, it works if any control is focus, just add to "Load Event"

KeyPreview=true