Register the global shortcut key implementation ideas and code _c# tutorials in WinForm and WPF

Source: Internet
Author: User

Shortcut key Helper class

Copy Code code as follows:

Class HotKey
{
<summary>
If the function executes successfully, the return value is not 0.
If the function fails to execute, the return value is 0. To get extended error messages, call GetLastError. net method: Marshal.GetLastWin32Error ()
</summary>
<param name= "HWnd" > Handle to the window where the hotkey is to be defined </param>
<param name= "id" > Define Hotkey ID (cannot be duplicated with other IDs) </param>
<param name= "Fsmodifiers" > identifies whether the hot key will take effect when pressing ALT, Ctrl, Shift, Windows, and so on </param>
<param name= "VK" > defines the contents of a hotkey, which can be converted using the Keys enumeration in WinForm.
The key enumeration in WPF is incorrect, you should use the System.Windows.Forms.Keys enumeration, or customize the correct enumeration or int constants </param>
<returns></returns>
[DllImport ("user32.dll", SetLastError = True)]
public static extern bool RegisterHotKey (
IntPtr HWnd,
int ID,
Keymodifiers Fsmodifiers,
int VK
);
<summary>
Cancel Registration Hotkey
</summary>
<param name= "HWnd" > Handle of Window to cancel hotkey </param>
<param name= "id" > id</param> to cancel the hotkey
<returns></returns>
[DllImport ("user32.dll", SetLastError = True)]
public static extern bool Unregisterhotkey (
IntPtr HWnd,
int ID
);
<summary>
Adds a string to the global atomic table and returns a unique identifier for the string, and success returns the newly created atomic ID, which fails back to 0
</summary>
<param name= "lpstring" ></param>
<returns></returns>
[DllImport ("kernel32", SetLastError = True)]
public static extern short Globaladdatom (string lpstring);
[DllImport ("kernel32", SetLastError = True)]
public static extern short Globaldeleteatom (short natom);
<summary>
Defines the name of a secondary key (converts a number to a character to make it easier to remember, but also removes the enumeration and uses the value directly)
</summary>
[Flags ()]
public enum Keymodifiers
{
None = 0,
Alt = 1,
Ctrl = 2,
Shift = 4,
WindowsKey = 8
}
<summary>
The corresponding message ID for the hotkey
</summary>
public const int wm_hotkey = 0x312;
}

WinForm Method
Registers an event in the onload in, and then overloads WndProc to handle the returned message
Copy Code code as follows:

int Alts,altd;
protected override void OnLoad (EventArgs e)
{
alts= hotkey.globaladdatom ("alt-s");
Altd= hotkey.globaladdatom ("alt-d");
Hotkey.registerhotkey (this. Handle, ALTs, HOTKEY.KEYMODIFIERS.ALT, (int) KEYS.S);
Hotkey.registerhotkey (this. Handle, Altd, HOTKEY.KEYMODIFIERS.ALT, (int) keys.d);
}
protected override void WndProc (ref message m)//Monitor Windows messages
{
Switch (m.msg)
{
Case Hotkey.wm_hotkey:
Processhotkey (m)//Call Processhotkey () function when the hot key is pressed
Break
}
Base. WndProc (ref m); Passing system messages from the WndProc of the parent class
}
Call this function when private void Processhotkey (message m)//key is pressed
{
INTPTR ID = m.wparam;//intptr Platform-specific type used to represent pointers or handles
int Sid=id. ToInt32 ();
if (sid==alts)
{
MessageBox.Show ("Press alt+s");
}
else if (SID==ALTD)
{
MessageBox.Show ("Press alt+d");
}
}

You can also use addmessagefilter add processing to replace overloaded WndProc in application, which enables the form itself to implement IMessageFilter interfaces.
Registration method
Copy Code code as follows:

[STAThread]
static void Main ()
{
Application.enablevisualstyles ();
Application.setcompatibletextrenderingdefault (FALSE);
var form = new Form1 ();
Application.addmessagefilter (form);
Application.Run (form);
}

implementing Interfaces
Copy Code code as follows:

BOOL Imessagefilter.prefiltermessage (ref message M)
{
const int Wm_hotkey = 0x0312;//if M. The value of MSG is 0x0312 so that the user presses the hotkey
Switch (m.msg)
{
Case Wm_hotkey:
Processhotkey (m)//Call Processhotkey () function when the hot key is pressed
Break
}
True if the message is filtered and the message is prevented from being dispatched, or false if the message is allowed to continue to the next filter or control
return false;
}

If messages are processed at both Addmessagefilter and WndProc, the order is imessagefilter first and then the WndProc
WPF Methods
The registration method in WPF is the same as WinForm, except that the value of the WPF key enumeration is not properly monitored. To refer to System.Windows.Forms.Keys or their own definition can be properly registered, window handles also need to come by the windowinterophelper, processing functions and WinForm different, need to hwndsource to add processing functions.
Registration and Processing methods
Copy Code code as follows:

int ALTs, Altd;
private void Window_Loaded (object sender, RoutedEventArgs e)
{
HwndSource HwndSource;
Windowinterophelper wih = new Windowinterophelper (this);
HwndSource = Hwndsource.fromhwnd (wih. Handle);
To add a handler
Hwndsource.addhook (MAINWINDOWPROC);
ALTs = Hotkey.globaladdatom ("Alt-s");
Altd = Hotkey.globaladdatom ("alt-d");
Hotkey.registerhotkey (wih. Handle, ALTs, HOTKEY.KEYMODIFIERS.ALT, (int) SYSTEM.WINDOWS.FORMS.KEYS.S);
Hotkey.registerhotkey (wih. Handle, Altd, HOTKEY.KEYMODIFIERS.ALT, (int) system.windows.forms.keys.d);
}
Private INTPTR Mainwindowproc (IntPtr hwnd, int msg, IntPtr wParam, IntPtr LParam, ref BOOL handled)
{
Switch (msg)
{
Case Hotkey.wm_hotkey:
{
int sid = Wparam.toint32 ();
if (sid = = ALTs)
{
MessageBox.Show ("Press alt+s");
}
else if (sid = = Altd)
{
MessageBox.Show ("Press alt+d");
}
handled = TRUE;
Break
}
}
return IntPtr.Zero;
}

Attention
If you register a shortcut key, the Fsmodifiers parameter in RegisterHotKey is 0, the None option, and some security software will alert you, possibly because it will allow you to monitor the keyboard globally, causing security problems
Code download

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.