Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Capture Combination Keys in Your Windows Forms Application

DZone's Guide to

Capture Combination Keys in Your Windows Forms Application

·
Free Resource
Often while writing a Windows application, it can be helpful to capture a combination of keys such as Ctrl-F1 or Alt-F2. This can be a requirement when showing/hiding some special option that you would not want available by default. So here is how to do just that.
To accomplish this task, the "ProcessDialogKey" function needs to be overridden as follows:
protected override bool ProcessDialogKey(Keys keyData)
{
// Declare a variable to keep track of the key modifiers (Ctrl,Alt,Shift,etc.)
string modifiers = "";

// Get the actual integer value of the keystroke
int keyCode = (int)keyData;

// Check to see if the control key is on
if ((keyCode & (int)Keys.Control) != 0)
{
modifiers += " ";
}

// Check to see if the alt key is on
if ((keyCode & (int)Keys.Alt) != 0)
{
modifiers += " ";
}

// Check to see if the shift key is on
if ((keyCode & (int)Keys.Shift) != 0)
{
modifiers += " ";
}

// Strip off the modifier keys
keyCode = keyCode & 0xFFFF;

// Attempt to convert the remaining bits to the enum name
Keys key = (Keys)keyCode;

if ((key != Keys.Menu) && (key != Keys.ControlKey) && (key != Keys.ShiftKey))
{
// If the user pressed the Ctrl-F1 combination
if (key == Keys.F1 && modifiers == " ")
{
// Do something special
}
}

// Return control to the base function
return base.ProcessDialogKey(keyData);
}
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}