c# WinForm 全局键盘事件怎么监听。。。。会的童鞋们贴上代码和用例吧,感激
2个回答
2013-05-21
展开全部
[DllImport("user32.dll")]private static extern int RegisterHotKey(IntPtr hwnd, int id, int fsModifiers, int vk);[DllImport("user32.dll")]private static extern int UnregisterHotKey(IntPtr hwnd, int id);int Space = 32; //热键ID private const int WM_HOTKEY = 0x312; //窗口消息-热键 private const int WM_CREATE = 0x1; //窗口消息-创建 private const int WM_DESTROY = 0x2; //窗口消息-销毁 private const int MOD_ALT = 0x1; //ALT private const int MOD_CONTROL = 0x2; //CTRL private const int MOD_SHIFT = 0x4; //SHIFT private const int VK_SPACE = 0x20; //SPACE 二、注册热键方法/// <summary> /// 注册热键 /// </summary> /// <param name="hwnd">窗口句柄</param> /// <param name="hotKey_id">热键ID</param> /// <param name="fsModifiers">组合键</param> /// <param name="vk">热键</param> private void RegKey(IntPtr hwnd, int hotKey_id, int fsModifiers, int vk){bool result;if (RegisterHotKey(hwnd,hotKey_id,fsModifiers,vk) == 0){result = false;}else{result = true;}if (!result){MessageBox.Show("注册热键失败!");}}/// <summary> /// 注销热键 /// </summary> /// <param name="hwnd">窗口句柄</param> /// <param name="hotKey_id">热键ID</param> private void UnRegKey(IntPtr hwnd, int hotKey_id){UnregisterHotKey(hwnd,hotKey_id);}三、重写WndProc方法,实现注册protected override void WndProc(ref Message m){base.WndProc(ref m);switch(m.Msg){case WM_HOTKEY: //窗口消息-热键 switch(m.WParam.ToInt32()){case 32: //热键ID MessageBox.Show("Hot Key : Ctrl + Alt + Shift + Space");break;default:break;}break;case WM_CREATE: //窗口消息-创建 RegKey(Handle,Space,MOD_ALT | MOD_CONTROL | MOD_SHIFT,VK_SPACE); //注册热键 break;case WM_DESTROY: //窗口消息-销毁 UnRegKey(Handle,Space); //销毁热键 break;default:break;}}
2013-05-21
展开全部
//所有的代码,所有的事件都是手写生成的namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Load +=new EventHandler(Form1_Load);//添加窗体加载事件
} private void Form1_Load(object sender, EventArgs e)
{
KeyDown += new KeyEventHandler(Form1_KeyDown);//添加按键事件
} private void Form1_KeyDown(object sender, KeyEventArgs e)
{
MessageBox.Show("You have press: " + e.KeyCode.ToString());
} }
} //按任意健,打印出键值
}
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Load +=new EventHandler(Form1_Load);//添加窗体加载事件
} private void Form1_Load(object sender, EventArgs e)
{
KeyDown += new KeyEventHandler(Form1_KeyDown);//添加按键事件
} private void Form1_KeyDown(object sender, KeyEventArgs e)
{
MessageBox.Show("You have press: " + e.KeyCode.ToString());
} }
} //按任意健,打印出键值
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询