1

My program binds "Z" key to a handler that activates a timer. That timer triggers a mouse click.

Problem is that if I keep Z pressed more than 5 seconds, it gets stuck and on KeyUp it doesn't fire, variable doesn't change to false and loop is endless, so it continues firing timer's callback when key is not pressed anymore. Only way to stop it is via ALT+F4

My code is at http://pastebin.com/rbCgY1rb

I use globalKeyboardHook from here

Critical part of code is:

 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";
            }

So question is: how to fix the freeze problem?

4

1 回答 1

1

Can you try checking the state of the timer before enabling/disabling it?

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;
    }
}
于 2013-07-15T07:24:36.280 回答