以一个form程序为例
public class form1 : form
{
private void form1_load(object sender, system.eventargs e)
{
sethotkey(false, false, false, true, keys.right, 100); // 设置多个热键
sethotkey(false, false, false, true, keys.space, 101);
sethotkey(false, false, false, true, keys.up, 102);
sethotkey(false, false, false, true, keys.down, 103);
}
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,int keyid)
{
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,keyid,modifier,nowkey);
}
catch
{
messagebox.show ("快捷键定义错误!");
}
}
protected override void wndproc(ref message msg )
{
const int wm_hotkey = 0x0312; // 热键消息
if (msg.msg != wm_hotkey)
{
base.wndproc(ref msg);
}
else
{
//激活热键,在此可以添加处理程序
if (100 == (int)msg.wparam)
{
//dosomething
}
else if (101 == (int)msg.wparam)
{
//dosomething
}
else if (102 == (int)msg.wparam)
{
//dosomething
}
else
{
//dosomething
}
}
}
private void form1_closing(object sender, system.componentmodel.canceleventargs e)
{
winhotkey.unregisterhotkey(handle, 100); // 注销热键
winhotkey.unregisterhotkey(handle, 101); // 注销热键
winhotkey.unregisterhotkey(handle, 102); // 注销热键
winhotkey.unregisterhotkey(handle, 103); // 注销热键
}
public class winhotkey
{
public 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
}
}
这样就完成了热键的定义
新闻热点
疑难解答