asp网站新闻置顶,设计素材网站免费的,网站服务器环境不支持mysql数据库,重庆设计网站建设开发环境#xff1a;VS2005, C#语言
为了给一个程序加一个系统级的热键#xff0c;在开发时需要使用到下面的代码#xff0c;就是在程序中注册和卸载热键。 1。首先在Form1类的函数中添加如下代码#xff1a;
[DllImport(user32.dll)] private static…开发环境VS2005, C#语言
为了给一个程序加一个系统级的热键在开发时需要使用到下面的代码就是在程序中注册和卸载热键。 1。首先在Form1类的函数中添加如下代码
[DllImport(user32.dll)] private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, Keys vk); [DllImport(user32.dll)] private static extern bool UnregisterHotKey(IntPtr hWnd, int id); 注意使用上面的代码前必须使用using System.Runtime.InteropServices;来引入命名空间。 2。在Form1的构造函数中注册热键
public Form1()
{ RegisterHotKey(Handle, 100, 0, Keys.Escape); //注册热键: Esc
} 3. 重写窗口的WndProc函数
protected override void WndProc(ref Message m) { if (m.Msg 0x312) { if (m.WParam.ToInt32() 100) this.Close(); //当按下Esc键时关闭本窗口 } base.WndProc(ref m); } 4。在析构函数中卸载热键
~Form1()
{ UnregisterHotKey(Handle, 100); //窗口未激活时卸载热键
} 这样就完成了我们的所有设置。但是这个添加的热键是系统级热键也就是说不管这个窗口有没有被激活这个热键都是能起作用的。 但是有时我们并不希望这种热键是系统级的而是希望当前窗口被激活时该热键才起作用如果没有被激活该热键不起作用。于是我想了办法就是更改热键注册和卸载的时间。
思路在Form1的Form1_Activated事件中注册热键在Form1_Deactivate中卸载热键其他不变代码如下
private void Form1_Activated(object sender, EventArgs e) { RegisterHotKey(Handle, 100, 0, Keys.Escape); //在窗口激活时注册热键: Esc } private void Form1_Deactivate(object sender, EventArgs e) { UnregisterHotKey(Handle, 100); //窗口未激活时卸载热键 } 这样就达到了窗口级的热键。 根据同样的思路你可以选择其他的时机来注册或卸载热键