110,538
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
class Hotkey
{
/// <summary>
/// 快捷键消息
/// </summary>
public const int WM_HOTKEY = 0x0312;
[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 );
[DllImport("kernel32.dll", EntryPoint = "GlobalAddAtomW")]
private static extern int GlobalAddAtomW(string name);
[Flags()]
public enum KeyModifiers
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8
}
public static int GlobalAddAtom(string name)
{
return GlobalAddAtomW(name) - 0xC000;
}
}
}
bool hotok1 = false;
int hotid1 = Hotkey.GlobalAddAtom("myhotkey1");
private void Form1_Load(object sender, EventArgs e)
{
hotok1 = Hotkey.RegisterHotKey(this.Handle, hotid1, Hotkey.KeyModifiers.None, Keys.F2);
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (hotok1)
{
Hotkey.UnregisterHotKey(this.Handle, hotid1);
}
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == Hotkey.WM_HOTKEY)
{
int id = m.WParam.ToInt32();
if (id == hotid1)
{
MessageBox.Show("热键消息来了");
}
}
}