Capturing Ctrl + Shift + P key stroke in a C# Windows Forms application [duplicate]
开发者_StackOverflow中文版Possible Duplicate:
Capture combination key event in a Windows Forms application
I need to perform a particular operation when (Ctrl + Shift + P) keys are pressed.
How can I capture this in my C# application?
Personally I think this is the simplest way.
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.Shift && e.KeyCode == Keys.P)
{
MessageBox.Show("Hello");
}
}
The following is not only a way to capture keystroke on your form, but it is in fact a way to add global Windows shortcuts.
1. Import needed libraries at the top of your class:
// DLL libraries used to manage hotkeys
[DllImport("user32.dll")] public static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vlc);
[DllImport("user32.dll")] public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
2. Add a field in your Windows Forms class that will be a reference for the hotkey in your code:
const int MYACTION_HOTKEY_ID = 1;
3. Register the hotkey (in the constructor of your Windows Forms for instance):
// Modifier keys codes: Alt = 1, Ctrl = 2, Shift = 4, Win = 8
// Compute the addition of each combination of the keys you want to be pressed
// ALT+CTRL = 1 + 2 = 3 , CTRL+SHIFT = 2 + 4 = 6...
RegisterHotKey(this.Handle, MYACTION_HOTKEY_ID, 6, (int)'P');
4. Handle the typed keys by adding the following method in your Windows Forms class:
protected override void WndProc(ref Message m) {
if (m.Msg == 0x0312 && m.WParam.ToInt32() == MYACTION_HOTKEY_ID) {
// My hotkey has been typed
// Do what you want here
// ...
}
base.WndProc(ref m);
}
You can use the KeyDownEvent with a lambda event handler:
Here is some more information about KeyDown. Read the article and think about the scope in which you want to have this behavior.
this.KeyDown += (object sender, KeyEventArgs e) =>
{
if (e.Control && e.Shift && e.KeyCode == Keys.P)
{
MessageBox.Show("pressed");
}
};
Use the GetKeyboardState API via P/Invoke. It returns an array representing the state of each virtual key recognised by Windows. If I'm not mistaken, you can cast the Keys enum to a byte and use it as an index as follows:
byte[] keys = new byte[256];
GetKeyboardState(keys);
bool isCtrlPressed = (keys[(byte)Keys.ControlKey] == 1);
-
Resources:
P/Invoke definition
MSDN documentation: GetKeyboardState function
精彩评论