我使用下面的代码来捕获ctrl + alt + Q热键,它们完美无缺。 但是,我想在后台应用程序中使用它。由于我的应用程序没有任何表单,我想在类文件中使用相同的代码。
我很困惑,因为我无法在类文件中编写事件处理程序[keypressed]。 相反,我想在线程中使用按键。
请帮忙。
public DialogResult Result;
KeyboardHook hook = new KeyboardHook();
public Form1()
{
InitializeComponent();
// register the event that is fired after the key press.
hook.KeyPressed += new EventHandler<KeyPressedEventArgs>(hook_KeyPressed);
// register the control + alt + F12 combination as hot key.
hook.RegisterHotKey((ModifierKeys)2 | (ModifierKeys)1, Keys.Q);
}
void hook_KeyPressed(object sender, KeyPressedEventArgs e)
{
Result = MessageBox.Show("Are you sure, you want to log off?","Log off"
,MessageBoxButtons.YesNo
,MessageBoxIcon.Warning);
if (Result == DialogResult.Yes)
{
}
else
{
}
}
答案 0 :(得分:2)
如果你想在没有表格的情况下捕捉全球热键,我恐怕你不能。
原因是全局热键被发送到窗口句柄(并在wndProc中处理,也称为消息泵)
因此,基本上Windows的工作方式,您无法使用没有表单的全局热键来接收它们。
我不完全确定这是你想要做的。但另一方面,没有任何形式的本地热键也没有,所以我看不出它可能是什么。
你可能想进一步澄清你的问题(没有冒犯)