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:


private void Form1_KeyDown(object sender, KeyEventArgs e)
if ((e.Control & e.Shift) && e.KeyCode == Keys.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");


Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs)
If (e.Control And e.Shift) AndAlso e.KeyCode = Keys.C Then
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, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal


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"