Recently, I found some documents about how to set the shortcut key running method or program in C #.
To set the shortcut key, you must use the two methods below user32.dll.
BOOL RegisterHotKey (
HWND hWnd,
Int id,
UINT fsModifiers,
UINT vk
);
And
BOOL UnregisterHotKey (
HWND hWnd,
Int id
);
To convert the code to C #, you must first reference the namespace System. Runtime. InteropServices; to load the unmanaged class user32.dll. So there is:
[DllImport ("user32.dll", SetLastError = true)]
Public static extern bool RegisterHotKey (
IntPtr hWnd, // handle to window
Int id, // hot key identifier
KeyModifiers fsModifiers, // key-modifier options
Keys vk // virtual-key code
);
[DllImport ("user32.dll", SetLastError = true)]
Public static extern bool UnregisterHotKey (
IntPtr hWnd, // handle to window
Int id // hot key identifier
);
[Flags ()]
Public enum KeyModifiers
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8
}
This is the method for registering and uninstalling the global shortcut key, so we only need to add the statement for registering the shortcut key when Form_Load, and uninstall the global shortcut key when FormClosing. At the same time, in order to ensure that the content of the clipboard is not affected by the call of the clipboard by other programs, I first cleared the content in the clipboard during Form_Load.
So there is:
Private void Form1_Load (object sender, System. EventArgs e)
{
Label2.AutoSize = true;
Clipboard. Clear (); // first Clear the Clipboard to prevent other contents from being copied in the Clipboard.
RegisterHotKey (Handle, 100, 0, Keys. F10 );
}
Private void form=formclosing (object sender, FormClosingEventArgs e)
{
UnregisterHotKey (Handle, 100); // uninstall the shortcut key
}
In other windows, how can we call my main process ProcessHotkey () after pressing the shortcut key?
Then we must rewrite the WndProc () method to call the process by monitoring system messages:
Protected override void WndProc (ref Message m) // monitor Windows messages
{
Const int WM_HOTKEY = 0x0312; // press the shortcut key
Switch (m. Msg)
{
Case WM_HOTKEY:
ProcessHotkey (); // call the main handler
Break;
}
Base. WndProc (ref m );
}