我在 Form1 的顶部做了这个:
globalKeyboardHook gkh;
在加载事件中:
private void Form1_Load(object sender, EventArgs e)
{
gkh = new globalKeyboardHook();
gkh.HookedKeys.Add(Keys.M);
gkh.KeyDown += new KeyEventHandler(gkh_KeyDown);
gkh.KeyUp += new KeyEventHandler(gkh_KeyUp);
}
然后在底部:
void gkh_KeyDown(object sender, KeyEventArgs e)
{
// e.KeyCode.ToString() is the KeyCode of the pressed key
e.Handled = true;
if ((e.KeyCode == System.Windows.Forms.Keys.LControlKey) || (e.KeyCode == System.Windows.Forms.Keys.RControlKey))
{
controlDown = true;
}
if (e.KeyCode == System.Windows.Forms.Keys.M && controlDown)
{
// Do CTRL-M action
if (mf == null)
{
//mf = new MagnifierMainForm();
mf = new MagnifierMainForm(false);
mf.StartPosition = FormStartPosition.Manual;
mf.Location = Control.MousePosition;
//mf.Show();
this.Select();
}
else if (mf.IsDisposed)
{
mf = new MagnifierMainForm(false);
mf.StartPosition = FormStartPosition.Manual;
mf.Location = Control.MousePosition;
//mf.Show();
}
else
{
mf.Close();
mf = null;
}
}
}
void gkh_KeyUp(object sender, KeyEventArgs e)
{
controlDown = false;
}
例如,当我运行我的应用程序并单击提示命令窗口然后单击 CTRL+M 或什至在几秒钟后不单击任何内容时,我遇到了异常:
CallbackOnCollectedDelegate 对“ScreenVideoRecorder!Utilities.globalKeyboardHook+keyboardHookProc::Invoke”类型的垃圾收集委托进行了回调。这可能会导致应用程序崩溃、损坏和数据丢失。将委托传递给非托管代码时,托管应用程序必须使它们保持活动状态,直到保证它们永远不会
检测到 CallbackOnCollectedDelegate 消息:对“ScreenVideoRecorder!Utilities.globalKeyboardHook+keyboardHookProc::Invoke”类型的垃圾收集委托进行了回调。这可能会导致应用程序崩溃、损坏和数据丢失。将委托传递给非托管代码时,托管应用程序必须使它们保持活动状态,直到保证它们永远不会被调用。