Creating button shortcuts in Windows Forms Applications

I recently created a Windows Forms Application and some of the feedback from users was they would like to have some shortcuts for certain buttons. At first I just assumed this was easy enough but when I started looking into it I realised there didn’t appear to be any out of the box functionality that would do this.

As I’m sure most people do I turned to Google and found that there wasn’t a way to handle this with out custom code. At first I looked at using the KeyDown event on the form but this didn’t quite work as expected so I managed to find an another article which suggested overriding the ProcessCmdKey method. I tried this and like magic it works, see code below.

To be honest I would expect this functionality to work without the need to write custom code but there isn’t much to it so its not too bad.


Code Snippet
  1. protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
  2.         {
  3.             switch(keyData)
  4.             {                
  5.                 case (Keys.Control | Keys.N):
  6.                     BtnTest1_Click(null, null);
  7.                     break;
  8.                 case (Keys.Control | Keys.S):
  9.                     BtnTest2_Click(null, null);
  10.                     break;
  11.                 case (Keys.Control | Keys.F):
  12.                     BtnTest3_Click(null, null);
  13.                     break;
  14.                 case (Keys.Control | Keys.G):
  15.                     BtnTest4_Click(null, null);
  16.                     break;
  17.                 case (Keys.Control | Keys.P):
  18.                     BtnTest5_Click(null, null);
  19.                     break;
  20.             }
  22.             return base.ProcessCmdKey(ref msg, keyData);
  23.         }


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: