Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing Ctrl + Shift + P key stroke in a C# Windows Forms application [duplicate]

Tags:

c#

winforms

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?

like image 353
Gaddigesh Avatar asked Oct 04 '11 16:10

Gaddigesh


Video Answer


2 Answers

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);
}
like image 135
Otiel Avatar answered Sep 30 '22 05:09

Otiel


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");
        }
    }
like image 24
Matt Avatar answered Sep 30 '22 05:09

Matt