Set shortcuts in c sharp

  • 2020-05-05 11:43:22
  • OfStack

Recently, I found some information about
, which is about setting shortcut keys in C # to run methods or programs
To set the shortcut keys, you must use the following two methods, user32.dll.

BOOL   RegisterHotKey(
HWND   hWnd
int   id
UINT   fsModifiers
UINT   vk
);  

And

BOOL   UnregisterHotKey(
HWND   hWnd
int   id
);  
To convert to C# code, you first reference the namespace System.Runtime.InteropServices; To load the unmanaged class user32.dll. Hence

[DllImport("user32.dll",   SetLastError=true)]  
public   static   extern   bool   RegisterHotKey(
IntPtr   hWnd,   //   handle   to   window 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 to register and uninstall the global shortcut key, so we only need to add the statement to register the shortcut key when Form_Load, and to uninstall the global shortcut key when FormClosing. At the same time, in order to ensure that the contents of the clipboard are not disturbed by other programs calling the clipboard, I first emptied the contents of the clipboard at Form_Load.

Hence

private   void   Form1_Load(object   sender,   System.EventArgs   e)
{
label2.AutoSize   =   true;

Clipboard. Clear (); // clean the clipboard first to prevent other contents from being copied in the clipboard first RegisterHotKey(Handle,   100,   0,   Keys.F10);
}

private   void   Form1_FormClosing(object   sender,   FormClosingEventArgs   e)
{
UnregisterHotKey (Handle   100); // uninstall
}  

So how can we call my main procedure ProcessHotkey() in another window after pressing the shortcut key?

Then we have to override the WndProc() method to call procedure:
by monitoring system messages
protected     void   WndProc(ref   Message   m)// monitor Windows message
{
const     WM_HOTKEY   =   0x0312; // press the shortcut key

switch   (m Msg) {
case   WM_HOTKEY:
ProcessHotkey (); // calls the main handler
break;
}
base. WndProc (ref   m);
}  

Related articles: