C # registering Windows hotkeys

Source: Internet
Author: User

Original: C # registering Windows Hotkey

Cackle:

A few days ago, a friend asked me how to implement the press F1 key to achieve the paste (Ctrl + V) function, Baidu a method, sent to him, he did not understand (already is the Boss of the yard), I did a demo to him reference. Today Hollow, will be a Demo to organize, as a collection, but also for everyone a reference.

Begin:

Registering a system hotkey, the. NET class library does not seem to provide a ready-made method, and requires the use of a system-supplied DLL.

Microsoft encapsulates many of the commonly used system functions in User32.dll, and the RegisterHotKey functions and Unregisterhotkey functions used to register the system hotkeys are also in the DLL file, so we need to map these two methods into a C # class. The following code encapsulates both methods and does some simple encapsulation, as follows:

1 usingSystem;2 usingSystem.Text;3 usingSystem.Runtime.InteropServices;4 usingSystem.Windows.Forms;5 6  Public classSystemhotkey7 {8     /// <summary>9     ///If the function executes successfully, the return value is not 0. Ten     ///If the function fails to execute, the return value is 0. To get the extended error message, call GetLastError.  One     /// </summary> A     /// <param name= "HWnd" >the handle of the window to define the hotkey</param> -     /// <param name= "id" >Define Hotkey ID (cannot be duplicated with other IDs)</param> -     /// <param name= "Fsmodifiers" >identifies whether the hotkey will take effect when pressing ALT, Ctrl, Shift, Windows, and other keys</param> the     /// <param name= "VK" >defining the contents of a hotkey</param> -     /// <returns></returns> -[DllImport ("user32.dll", SetLastError =true)] -      Public Static extern BOOLRegisterHotKey (IntPtr hWnd,intID, keymodifiers fsmodifiers, Keys VK); +  -     /// <summary> +     ///Logout Hotkey A     /// </summary> at     /// <param name= "HWnd" >handle of the window to cancel the hotkey</param> -     /// <param name= "id" >the ID of the hotkey to cancel</param> -     /// <returns></returns> -[DllImport ("user32.dll", SetLastError =true)] -      Public Static extern BOOLUnregisterhotkey (IntPtr hWnd,intID); -  in     /// <summary> -     ///The name of the secondary key.  to     ///Alt, Ctrl, Shift, WindowsKey +     /// </summary> - [Flags ()] the      Public enumkeymodifiers {None =0, Alt =1, Ctrl =2, Shift =4, WindowsKey =8 } *  $     /// <summary>Panax Notoginseng     ///Register Hotkey -     /// </summary> the     /// <param name= "hwnd" >window Handle</param> +     /// <param name= "hotkey_id" >Hotkey ID</param> A     /// <param name= "Keymodifiers" >Key Combinations</param> the     /// <param name= "key" >Hotkey</param> +      Public Static voidReghotkey (INTPTR hwnd,intHotkeyid, Keymodifiers keymodifiers, Keys key) -     { $         if(!RegisterHotKey (hwnd, Hotkeyid, Keymodifiers, key)) $         { -             intErrorCode =Marshal.GetLastWin32Error (); -             if(ErrorCode = =1409) the             { -MessageBox.Show ("hot keys are occupied! ");Wuyi             } the             Else -             { WuMessageBox.Show ("Register Hotkey failed! Error code:"+errorCode); -             } About         } $     } -  -     /// <summary> -     ///Logout Hotkey A     /// </summary> +     /// <param name= "hwnd" >window Handle</param> the     /// <param name= "hotkey_id" >Hotkey ID</param> -      Public Static voidUnreghotkey (INTPTR hwnd,intHotkeyid) $     { the         //unregister the specified hotkey the Unregisterhotkey (hwnd, Hotkeyid); the     } the  -}

(This class is online search, here to borrow ...) Thank the original author here! )

In the above class, only two static methods Reghotkey and Unreghotkey are required to register and unregister the hotkey.

One thing to note here: These two methods require a window handle to bind the system hotkey message, that is, when the user presses the registered hotkey, the key message is sent to the specified window.

Reghotkey method has four parameters, the first is a window handle, the second is a custom hotkey ID, the third is a combination of keys, such as CTRL, ALT, SHIFT, etc., if not, is none, the fourth is the specified hotkey.

The Unreghotkey method simply requires a window handle and a hotkey ID to unregister the hotkey.

Then, create a form and add the following code in the Code view:

        Private Const intWm_hotkey =0x312;//window message: Hotkey        Private Const intWm_create =0x1;//window messages: Creating        Private Const intWm_destroy =0x2;//window messages: destroying        Private Const intHotkeyid =1;//Hotkey ID (custom)        protected Override voidWndProc (refMessage msg) {            Base. WndProc (refmsg); Switch(Msg. MSG) { CaseWm_hotkey://window message: Hotkey                    intTmpwparam =Msg.                    Wparam.toint32 (); if(Tmpwparam = =Hotkeyid) {System.Windows.Forms.SendKeys.Send ("^v"); }                     Break;  CaseWm_create://window messages: CreatingSystemhotkey.reghotkey ( This.                    Handle, Hotkeyid, SystemHotKey.KeyModifiers.None, KEYS.F1);  Break;  CaseWm_destroy://window messages: destroyingSystemhotkey.unreghotkey ( This. Handle, Hotkeyid);//destroying Hotkeys                     Break; default:                     Break; }        }

In the above code, the values of the three constants of Wm_hotkey, Wm_create, Wm_destroy are system-defined without concern. Hotkeyid is a custom value that is used to distinguish between different hotkey processing logic when multiple hotkeys are registered, and the system passes the value as a parameter to the handler when the user touches the hot key.

In addition, the above code overrides a system method WndProc, this method called "window process" (refer to Baidu Encyclopedia), used to receive processing registered to the form of all the events, including form creation, form destruction, System hotkeys and so on. The method has a message struct parameter that encapsulates some of the basic properties of Windows messages, such as message IDs, parameters, and so on.

The above code registers the hotkey F1 when the method receives the window creation message, and unregisters the hotkey when the message is received by the window, and, when the system hotkey message is received, confirms that the action we want is triggered according to the message parameter (Hotkey ID), for example, the analog user here presses the CTRL + V key.

Finally, running the program, you can use the F1 key in any application to complete the CTRL + V effect.

C # registering Windows hotkeys

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.