首页 > 解决方案 > 为什么在方法完成后处理我的键盘事件?

问题描述

单击按钮后,我试图:

...最终结果应该是框中的“12”。

当我没有任何延迟地运行程序时,它会按预期工作......尽管速度很快。

当我尝试在 1 和 2 之间设置延迟时,我看到没有处理单击或键盘事件并出现在表单上,​​直到方法完成。文本框更改将从 2 变为 4 再到 6。

文本框达到6后,输入框中会出现“12”。在我看来,这两次都像,在方法中的所有代码都完成执行之前不会发生任何事件。

以我有限的知识,我试图理解:

  1. 为什么会这样?
  2. 如何在事件之间的方法中间暂停而不冻结整个表单?
  3. 如何让每个事件出现在下一个事件之前,而不是在方法完成时发生所有事件?
public void DelayTimer(int interval)
        {
            Task.Delay(interval).Wait();
        }
private void typeButton_Click(object sender, EventArgs e)
        {
            CursorMovementToPoint(PointToScreen(new Point((typeBox.Location.X + (typeBox.Size.Width / 2)), (typeBox.Location.Y + (typeBox.Size.Height / 2))))); // Moves cursor to center of Box
            textBox1.Text = "1"; // Indicates event 1 is done
            mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, Cursor.Position.X, Cursor.Position.Y, 0, 0); // Clicks on box
            textBox1.Text = "2"; // Indicates event 2 is done
            DelayTimer(1000); // Pauses for 1 sec
            textBox1.Text = "3"; // Indicates pause is done
            keybd_event(KEY_1, KEY_1_SCAN, 0, 0); // Types "1" into Box
            textBox1.Text = "4";
            DelayTimer(1000); // Pauses for 1 sec between typing "1" and before typing "2"
            textBox1.Text = "5";
            keybd_event(KEY_2, KEY_2_SCAN, 0, 0); // Types "2" into Box
            textBox1.Text = "6"; // Finished
        }

标签: c#winforms

解决方案


现在Button.Click声明了处理程序async
DelayTimer()方法被删除,延迟直接放置在typeButton_Click事件处理程序中。
这实质上将延迟从 更改Task.Delay(1000).Wait();await Task.Delay(1000);

private async void typeButton_Click(object sender, EventArgs e)
{
    CursorMovementToPoint(PointToScreen(new Point((typeBox.Location.X + (typeBox.Size.Width / 2)), (typeBox.Location.Y + (typeBox.Size.Height / 2)))));
    SendM(MOUSEEVENTF.LEFTDOWN | MOUSEEVENTF.LEFTUP);
    textBox1.Text = "1";
    await Task.Delay(1500);

    SendK(ScanCodeShort.KEY_1);
    textBox1.Text = "2";
    await Task.Delay(1500);

    SendK(ScanCodeShort.KEY_2);
    textBox1.Text = "3";
}

这解决了问题:在方法完成之前没有处理事件,表单没有被阻止并且可以处理其他事件(现在我也可以在延迟处于活动状态时关闭表单)。
我还添加SendInput()了替换我以前调用鼠标和键盘事件的方法,但这与延迟问题无关。为我工作。


推荐阅读