-
-
Notifications
You must be signed in to change notification settings - Fork 208
Hot Keys
Jacob Fliss edited this page Sep 6, 2019
·
7 revisions
Add Interop Services above the namespace:
using System.Runtime.InteropServices;
Add the following to the form class:
#region DllImports
[DllImport("user32.dll")]
public static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, uint vlc);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
#endregion
protected override void WndProc(ref Message msg)
{
if (msg.Msg == 0x0312) //our hot button recognition and function triggering
{
int id = msg.WParam.ToInt32();
if (id == 1) { //our designated ID to execute
execFunction(); //our function to execute
}
if (id == 2) { //our designated ID to execute
execSecondFunction(); //our second function to execute
}
}
base.WndProc(ref msg);
}
In your form load or initialize function register the hotkey like so:
public Form1()
{
RegisterHotKey(this.Handle, 1, 0x0002, '1'); //hold down CTRL (0x0002) and press 1 key, trigger ID 1 in WndProc
RegisterHotKey(this.Handle, 2, 0x0000, '2'); //second example. Just press 2 key, trigger ID 2 in WndProc
}
Our execFunction(). This is just an example function, change it to whatever you want:
void execFunction() {
MessageBox.Show("You pressed the hotkey!");
}
void execSecondFunction() {
MessageBox.Show("You pressed the 2nd hotkey!");
}