C # implement shortcut key (system hotkey) Response
In applications, we may need to implement shortcut keys such as Ctrl + C copy and CTRL + V paste. This article briefly introduces its implementation and provides an implementation class.
(1) create a class file named hotkey. CS,CodeAs follows:
Using system;
Using system. Collections. Generic;
Using system. runtime. interopservices;
Using system. Windows. forms;
Namespace koalastudio. bookshopmanager
{
Class hotkey
{
// If the function is successfully executed, the return value is not 0.
// If the function fails to be executed, the return value is 0. To get the extended error message, call getlasterror.
[Dllimport ("user32.dll", setlasterror = true)]
Public static extern bool registerhotkey (
Intptr hwnd, // handle of the window for which the hotkey is to be defined
Int ID, // define the hotkey ID (cannot be the same as other IDS)
Keymodifiers fsmodifiers, // identifies whether the hot key takes effect only when you press ALT, Ctrl, shift, or windows.
Keys VK // defines the content of the Hot Key
);
[Dllimport ("user32.dll", setlasterror = true)]
Public static extern bool unregisterhotkey (
Intptr hwnd, // handle of the window to which the hotkey is to be canceled
Int ID // ID of the hotkey to be canceled
);
// Defines the name of the secondary key (convert a number into a character for memory, or use a value directly for this enumeration)
[Flags ()]
Public Enum keymodifiers
{
None = 0,
Alt = 1,
CTRL = 2,
Shift = 4,
Windowskey = 8
}
}
}
Brief description:
The "public static extern bool registerhotkey ()" function is used to register hotkeys. This function can be used only after the dynamic link library of user32.dll is referenced.
User32.dll is a non-hosted code and cannot be directly referenced in the namespace. Therefore, you need to use "dllimport" before using it. Therefore, you need to add
"[Dllimport (" user32.dll ", setlasterror = true.
The "public static extern bool unregisterhotkey ()" function is used to deregister the hotkey. Similarly, you must use dllimport to reference user32.dll before using it.
"Public Enum keymodifiers {}" defines a set of enumerations. The numeric code of the secondary key is directly expressed as text for ease of use. In this way, we do not have to remember every secondary
You only need to select the name of the Code.
(2) take form forma as an example to introduce the use of the hotkey class.
register the hotkeys in the activate event of forma. In this example, register the three hotkeys SHIFT + S, CTRL + Z, ALT + D. The ID number can be set as needed, but it must not be repeated.
private void form_activated (Object sender, eventargs e)
{< br> // register the hotkey SHIFT + S, ID: 100. Hotkey. keymodifiers. Shift can also be expressed directly by number 4.
hotkey. registerhotkey (handle, 100, hotkey. keymodifiers. Shift, keys. s);
// register the hot key Ctrl + B and the ID number is 101. Hotkey. keymodifiers. CTRL can also be expressed directly by number 2.
hotkey. registerhotkey (handle, 101, hotkey. keymodifiers. Ctrl, keys. B);
// register the hot key Alt + D with the ID 102. Hotkey. keymodifiers. ALT can also be expressed by the number 1.
hotkey. registerhotkey (handle, 102, hotkey. keymodifiers. ALT, keys. d);
}
Unregister the hotkey from the leave event of forma.
Private void frmsale_leave (Object sender, eventargs E)
{
// Deregister the hotkey setting with ID 100
Hotkey. unregisterhotkey (handle, 100 );
// Deregister the hotkey setting with ID 101
Hotkey. unregisterhotkey (handle, 101 );
// Deregister the hotkey setting with ID 102
Hotkey. unregisterhotkey (handle, 102 );
}
Reload the wndproc function in froma.
///
/// Monitor Windows messages
/// Reload the wndproc Method for hotkey response
///
///
Protected override void wndproc (ref message m)
{
Const int wm_hotkey = 0x0312;
// Press the shortcut key
Switch (M. msg)
{
Case wm_hotkey:
Switch (M. wparam. toint32 ())
{
Case 100: // SHIFT + S
// Enter the shortcut key response code.
Break;
Case 101: // press Ctrl + B.
// Enter the shortcut key response code.
Break;
Case 102: // Alt + D is pressed
// Enter the shortcut key response code.
Break;
}
Break;
}
Base. wndproc (ref m );
}
After the code is complete, when we press SHIFT + S, CTRL + B, ALT + D in the form,ProgramWill make a response.
To set the shortcut key, you must use the two methods below user32.dll. Bool registerhotkey (// Register the system's hotkey API functions Hwnd, Int ID, Uint fsmodifiers, Uint VK ); Bool unregisterhotkey (// Delete the system hotkey API Function Hwnd, Int ID ); REFERENCE The namespace system. runtime. interopservices; in C # to load the unmanaged class user32.dll.
Using System; Using System. Collections. Generic; Using System. componentmodel; Using System. Data; Using System. drawing; Using System. text; Using System. Windows. forms; Namespace Hotkey { Public Enum Keymodifiers // Key combination Enumeration { None = 0, Alt = 1, Control = 2, Shift = 4, Windows = 8 } Public Partial Class Form1:Form { /* * Registerhotkey Function prototype and description: * Bool registerhotkey ( * Hwnd, // window to receive hot-key notification * Int ID, // identifier of Hot Key * Uint fsmodifiers, // key-modifier flags * Uint VK // virtual-key code ); * The parameter ID is an ID value defined for you. * For a thread, the value must be within the range of 0x0000-0xbfff, And the decimal value is 0 ~ 49151 * The DLL value must be in the range of 0xc000-0 xFFFF, And the decimal value is 49152 ~ 65535 * In the same process, this value must be unique. The fsmodifiers parameter specifies the key used together with the hotkey. * Optional values: mod_alt mod_control mod_win mod_shift, 0: None, 1: ALT, 2: control, 4: shift, 8: Windows * VK Specifies the virtual key code of the hotkey. */ [System. runtime. interopservices.Dllimport("User32.dll")]// Declare API functions Public Static Extern BoolRegisterhotkey ( IntptrHwnd,// Handle to window IntID,// Hot Key Identifier UintFsmodifiers,// Key-modifier options KeysVK// Virtual-key code ); [System. runtime. interopservices.Dllimport("User32.dll")]// Declare API functions Public Static Extern BoolUnregisterhotkey ( IntptrHwnd,// Handle to window IntID// Hot Key Identifier ); PublicForm1 () { Initializecomponent (); } Private VoidProcesshotkey (MessageM)// Call this function when you press the specified key. { IntptrId = M. wparam;// Intptr Platform-specific type used to indicate pointers or handles // MessageBox. Show (Id. tostring ()); StringSID = ID. tostring (); Switch(SID) { Case "100": MessageBox. Show (" Call function" ); Break; Case "200": MessageBox. Show (" Call function B" ); Break; } } Private VoidForm1_load (ObjectSender,EventargsE) { // Handle Is the handle of the current window, continue from control. Handle, control is the base class of the definition Control // Registerhotkey (handle, 100, 0, keys. );// Register the shortcut key. The hot key is. // Registerhotkey (handle, 100, keymodifiers. Alt | keymodifiers. Control, keys. B );// At this time, the hot key is Alt + Ctrl + B. // Registerhotkey (handle, 100, 1, keys. B); // 1 Is the Alt key, and the hot key is Alt + B Registerhotkey (handle, 100, 2,Keys. );// Defines the hot key as ALT + TAB. Here the Alt + Tab key of the screen system is implemented. Registerhotkey (handle, 200, 2,Keys. B );// Register two hotkeys and determine the function to be executed based on the ID value 100,200. } Private VoidButton#click (ObjectSender,EventargsE)// Reset the hotkey { Unregisterhotkey (handle, 100 );// Uninstall shortcuts Registerhotkey (handle, 100, 2,Keys. C );// Register a new shortcut key. parameter 0 indicates no combination key. } Private VoidForm1_formclosing (ObjectSender,FormclosingeventargsE)// The hotkey is retained when you exit the program. { Unregisterhotkey (handle, 100 );// Uninstall 1st shortcut keys Unregisterhotkey (handle, 200 );// Contains 2nd shortcut keys } // Rewrite the wndproc () method and call the process by monitoring system messages. Protected Override VoidWndproc (Ref MessageM)// Monitoring Windows messages { Const IntWm_hotkey = 0x0312;// If M. MSG is 0x0312, the user presses the hot key. Switch(M. msg) { CaseWm_hotkey: Processhotkey (m );// Call the processhotkey () function when you press the hot key. Break; } Base. Wndproc (RefM );// Pass the system message from the wndproc of the parent class } } }