注册全局热键

Posted on 2005-07-09 16:21  flourish  阅读(623)  评论(0)    收藏  举报
  像QQ那样,注册全局热键
你在程序中需要自己注册全局热键,
用到API
RegisterHotKey
UnregisterHotKey
首先,创建一个WinHotKey类,如下
public class WinHotKey
{
[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
}
public WinHotKey()
{
// TODO: 在此处添加构造函数逻辑
}
}
然后,在程序中这样调用
//快捷键定义
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
{
//login.ShowMessage("快捷键定义错误!");
}
}
//激活热键
protected override void WndProc(ref Message m )
{
const int WM_HOTKEY = 0x0312; 
switch(m.Msg) 

case WM_HOTKEY: 
{
//如果有新消息,弹出消息
if( ReceiveNewMessage == true)
{
for(int i=0;i {
ManInfor searchMan = (ManInfor)this.manInforList;
if( searchMan.manInforID.Equals( getFriendID))
{
searchMan.Clicked = true;
searchMan.P2PShow();
break;
}
}
}
else
{
this.Show();
this.TopMost = true;
this.panel_Main.Refresh();
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
}
}
break; 

base.WndProc(ref m );

博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3