程序冻结,定时器循环无休止
本文关键字:循环 无休止 定时器 冻结 程序 | 更新日期: 2023-09-27 18:22:23
我的程序将"Z"键绑定到激活计时器的处理程序。计时器触发鼠标点击。
问题是,如果我按住Z超过5秒,它就会被卡住,在KeyUp上它不会触发,变量不会变为false
,循环是无休止的,所以当键不再按下时,它会继续触发计时器的回调。阻止它的唯一方法是通过ALT+F4
我的代码在http://pastebin.com/rbCgY1rb
我从这里使用globalKeyboardHook
代码的关键部分是:
private void keyDownCallback(object sender, KeyEventArgs e) {
if (e.KeyCode.ToString() == "Z") {
timer1.Enabled = true;
this.forceNoLoop = false;
} else if(e.KeyCode.ToString() == "X") {
timer1.Enabled = false;
this.forceNoLoop = true;
}
}
private void keyUpCallback(object sender, KeyEventArgs e) {
timer1.Enabled = false;
this.forceNoLoop = true;
}
private void timer1_Tick(object sender, EventArgs e) {
if (forceNoLoop) return;
mouse_event(MOUSEEVENTF_LEFTDOWN, (uint)Cursor.Position.X, (uint)Cursor.Position.Y, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, (uint)Cursor.Position.X, (uint)Cursor.Position.Y, 0, 0);
lblClickStatus.Text = "clicked " + (this.clickTimes++) + " times";
}
所以问题是:如何解决冻结问题?
在启用/禁用计时器之前,可以尝试检查计时器的状态吗?
private void keyDownCallback(object sender, KeyEventArgs e) {
if (e.KeyCode.ToString() == "Z") {
if (!timer1.Enabled)
timer1.Enabled = true;
} else if (e.KeyCode.ToString() == "X") {
if (timer1.Enabled)
timer1.Enabled = false;
}
}