Add a hotkey for your program (C #)

Source: Internet
Author: User

Form1.cs

Private void form1_load (Object sender, system. eventargs E)
{
// Set the hotkey
Sethotkey (false, keys. space );
}

Private bool key_ctrl = false;
Private bool key_shift = false;
Private bool key_alt = false;
Private bool key_windows = false;
Private Keys key_other;

Public void sethotkey (bool bctrl, bool bshift, bool Balt, bool bwindows, keys nowkey)
{
Try
{
This. key_alt = Balt;
This. key_ctrl = bctrl;
This. key_shift = bshift;
This. key_windows = bwindows;
This. key_other = nowkey;

Winhotkey. keymodifiers modifier = winhotkey. keymodifiers. None;

If (this. key_ctrl)
Modifier | = winhotkey. keymodifiers. Control;
If (this. key_alt)
Modifier | = winhotkey. keymodifiers. ALT;
If (this. key_shift)
Modifier | = winhotkey. keymodifiers. shift;
If (this. key_windows)
Modifier | = winhotkey. keymodifiers. windows;

Winhotkey. registerhotkey (handle, 100, modifier, nowkey );
}
Catch
{
MessageBox. Show ("incorrect definition of the shortcut key! ");
}
}

Protected override void wndproc (ref message MSG)
{
Const int wm_hotkey = 0x0312; // hotkey message

If (msg. MSG! = Wm_hotkey)
{
Base. wndproc (ref MSG );
}
Else
{
MessageBox. Show ("hotkey pressed"); // activate the hotkey
// Processhotkey ();
}
}

Private void form1_closing (Object sender, system. componentmodel. canceleventargs E)
{
Winhotkey. unregisterhotkey (handle, 100); // cancel the hotkey
}

Winhotkey. CS

public class winhotkey
{< br> Public winhotkey ()
{< br>
}

[dllimport ("user32.dll", setlasterror = true)]
Public static extern bool registerhotkey (
intptr hwnd,
int ID,
keymodifiers fsmodifiers,
keys VK
);

[dllimport ("user32.dll", setlasterror = true)]
Public static extern bool unregisterhotkey (
intptr hwnd,
int id
);

[Flags ()]
Public Enum keymodifiers
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8
}

}

Download complete source code

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.