C # implement global shortcut key (system hotkey) response)

Source: Internet
Author: User

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 hotkey API Function
Hwnd,
Int ID,
Uint fsmodifiers,
Uint VK
);

Bool unregisterhotkey (// API function used to delete the system hotkey
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 );
* Parameter ID is an ID value defined for you
* For a thread, the value must be in the range of 0x0000-0xbfff, And the decimal value is 0 ~ 49151
* For DLL, the 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, or 0: none; 1: ALT; 2: control; 4: shift; 8: Windows
* VK indicates the virtual key code of the hotkey.
*/

[System. runtime. interopservices. dllimport ("user32.dll")] // declare an API Function
Public static extern bool registerhotkey (
Intptr hwnd, // handle to window
Int ID, // Hot Key Identifier
Uint fsmodifiers, // key-modifier options
Keys VK // virtual-key code
);
[System. runtime. interopservices. dllimport ("user32.dll")] // declare an API Function
Public static extern bool unregisterhotkey (
Intptr hwnd, // handle to window
Int ID // Hot Key Identifier
);
Public form1 ()
{
Initializecomponent ();
}
Private void processhotkey (message m) // call this function when you press the set key.
{
Intptr // intptr indicates the platform-specific type of the pointer or handle
// MessageBox. Show (Id. tostring ());
String SID = ID. tostring ();
Switch (SID)
{
Case "100 ":
MessageBox. Show ("call function ");
Break;
Case "200 ":
MessageBox. Show ("call function B ");
Break;
}
}
Private void form1_load (Object sender, eventargs E)
{
// Handle is the handle of the current window, and continues from control. Handle. Control is the base class of the control defined.
// Registerhotkey (handle, 100, 0, keys. a); // register the shortcut key. The hot key is.
// Registerhotkey (handle, 100, keymodifiers. Alt | keymodifiers. Control, keys. B); // 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. a); // 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 which function to execute Based on the ID value 100,200.
}

Private void button#click (Object sender, eventargs e) // reset the hotkey
{
Unregisterhotkey (handle, 100); // uninstall the shortcut key
Registerhotkey (handle, 100, 2, keys. c); // register a new shortcut key. parameter 0 indicates no combination key.
}

Private void form=formclosing (Object sender, formclosingeventargs e) // The hotkey is loaded when the program exits.
{
Unregisterhotkey (handle, 100); // uninstall the 1st shortcut keys
Unregisterhotkey (handle, 200); // contains 2nd shortcut keys
}

// 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; // if the value of M. MSG is 0x0312, the user presses the hot key.
Switch (M. msg)
{
Case wm_hotkey:
Processhotkey (m); // call the processhotkey () function when the hot key is pressed.
Break;
}
Base. wndproc (ref m); // transmits the system message from the wndproc of the parent class.
}
}
}

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.