October 8, 2009

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.

'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

2 Responses to "Detecting Ctrl and Shift Keys on a Form using C# or VB.NET"
  1. Anonymous said...
    December 24, 2009 6:36 AM

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

  2. Anonymous said...
    July 27, 2011 10:32 AM

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

    KeyPreview=true

 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions