08 Oct

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

comments

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

Share:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • DZone
  • LinkedIn
  • Reddit
  • StumbleUpon
  • Twitthis

From DevCurry

Leave a Reply

Spam Protection by WP-SpamFree

Categories