C # register Windows hotkeys,

Source: Internet
Author: User

C # register Windows hotkeys,

Idle:

A friend asked me how to press the F1 key to implement the paste (Ctrl + V) function a few days ago. Baidu sent a method to him, he can't understand it (he is a former codenon of Boss), so I made a Demo for his reference. Today is empty. I will sort out the Demo for your reference.

 

Begin:

Register the system hotkey. the. net class library does not seem to provide a ready-made method. You need to use the DLL provided by the system.

Microsoft encapsulates many common system functions in user32.dll, and registers the RegisterHotKey function and UnregisterHotKey function used by the system hotkey, therefore, we need to map the two methods to the C # class. The following code encapsulates the two methods and makes some simple encapsulation, as follows:

1 using System; 2 using System. text; 3 using System. runtime. interopServices; 4 using System. windows. forms; 5 6 public class SystemHotKey 7 {8 // <summary> 9 // if the function is successfully executed, the return value is not 0. 10 /// if the function fails to be executed, the return value is 0. To get the extended error message, call GetLastError. 11 /// </summary> 12 /// <param name = "hWnd"> handle of the window to which the hotkey is to be defined </param> 13 /// <param name =" id "> define the hotkey ID (cannot be the same as other IDS) </param> 14 // <param name = "fsModifiers"> indicates whether the hotkey takes effect only when Alt, Ctrl, Shift, or Windows are pressed. </param> 15/ // <param name = "vk"> define the content of the hotkey </param> 16 // <returns> </returns> 17 [DllImport ("user32.dll ", setLastError = true)] 18 public static extern bool RegisterHotKey (IntPtr hWnd, int id, KeyModifiers fsModifiers, Keys vk ); 19 20 /// <summary> 21 /// cancel hotkey 22 /// </summary> 23 // <param name = "hWnd"> handle </param> 24 // <param name = "id"> ID of the hotkey to be canceled </param> 25 /// <returns> </returns> 26 [DllImport ("user32.dll ", setLastError = true)] 27 public static extern bool UnregisterHotKey (IntPtr hWnd, int id); 28 29 // <summary> 30 // secondary key name. 31 // Alt, Ctrl, Shift, WindowsKey32 /// </summary> 33 [Flags ()] 34 public enum KeyModifiers {None = 0, Alt = 1, ctrl = 2, Shift = 4, windowsKey = 8} 35 36 /// <summary> 37 // register the hotkey 38 /// </summary> 39 /// <param name = "hwnd"> window handle </param> 40 // <param name = "hotKey_id"> hotkey ID </param> 41 // <param name = "keyModifiers"> key combination </param> 42 /// <param name = "key"> hotkey </param> 43 public static void RegHotKey (IntPtr hwnd, Int hotKeyId, KeyModifiers keyModifiers, Keys key) 44 {45 if (! RegisterHotKey (hwnd, hotKeyId, keyModifiers, key) 46 {47 int errorCode = Marshal. getLastWin32Error (); 48 if (errorCode = 1409) 49 {50 MessageBox. show ("Hot Key occupied! "); 51} 52 else53 {54 MessageBox. Show (" An error occurred while registering the hotkey! Error Code: "+ errorCode ); 55} 56} 57} 58 59 // <summary> 60 // deregister the hotkey 61 /// </summary> 62 /// <param name = "hwnd"> window handle </param> 63 // <param name = "hotKey_id"> hotkey ID </param> 64 public static void UnRegHotKey (IntPtr hwnd, int hotKeyId) 65 {66 // deregister the specified hotkey 67 UnregisterHotKey (hwnd, hotKeyId); 68} 69 70}

(This class is found on the Internet. I will borrow it here... Thank you to the original author !)

In the above class, you only need to use two static methods, RegHotKey and UnRegHotKey, to register and deregister the hotkey.

Note that the two methods require a window handle to bind the system hotkey message. That is to say, after you press the registered hotkey, the system sends the key message to the specified window.

The RegHotKey method has four parameters: the first is the window handle, the second is the custom hotkey ID, and the third is the combination key, such as Ctrl, Alt, Shift, and so on. If not, it is None, the fourth is the specified hot key.

The UnRegHotKey method can unregister the hotkey by using the window handle and hotkey ID.

 

Create a form and add the following code to the Code view:

Private const int WM_HOTKEY = 0x312; // window message: hotkey private const int WM_CREATE = 0x1; // window message: create private const int WM_DESTROY = 0x2; // window Message: destroy private const int HotKeyID = 1; // hotkey ID (custom) protected override void WndProc (ref Message msg) {base. wndProc (ref msg); switch (msg. msg) {case WM_HOTKEY: // window message: hotkey int tmpWParam = msg. WParam. toInt32 (); if (tmpWParam = HotKeyID) {System. windows. forms. sendKeys. send ("^ v");} break; case WM_CREATE: // window message: Create SystemHotKey. regHotKey (this. handle, HotKeyID, SystemHotKey. keyModifiers. none, Keys. f1); break; case WM_DESTROY: // window message: Destroy SystemHotKey. unRegHotKey (this. handle, HotKeyID); // destroy the hotkey break; default: break ;}}

In the above Code, the values of the three constants WM_HOTKEY, WM_CREATE, and WM_DESTROY are defined by the system. HotKeyID is a custom value used to distinguish the processing logic of different hotkeys when multiple hotkeys are registered, the system will pass this value as a parameter to the handler when the user triggers the hot key.

In addition, a system method WndProc is rewritten in the above Code. This method is called "window process" (refer to Baidu encyclopedia) and is used to receive and process all events registered to the form, including form creation, form destruction, and system hotkeys. This method has a Message struct parameter, which encapsulates some basic attributes of Windows messages, such as Message ID and parameters.

The above code registers the hotkey F1 when the method receives the window creation message, and cancels the hotkey when receiving the window destruction message, and receives the system hotkey message, confirm the action we want to trigger Based on the message parameter (hotkey ID). For example, press Ctrl + V for the simulated user here.

 

Finally, run the program to use the F1 key in any application to complete the Ctrl + V effect.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.