c# - 为什么在方法完成后处理我的键盘事件?
问题描述
单击按钮后,我试图:
- 将光标移动到输入框。
- 单击该框。
- 暂停 x 次。
- 键入“1”。
- 暂停 x 次。
- 在框中键入“2”。
...最终结果应该是框中的“12”。
当我没有任何延迟地运行程序时,它会按预期工作......尽管速度很快。
当我尝试在 1 和 2 之间设置延迟时,我看到没有处理单击或键盘事件并出现在表单上,直到方法完成。文本框更改将从 2 变为 4 再到 6。
文本框达到6后,输入框中会出现“12”。在我看来,这两次都像,在方法中的所有代码都完成执行之前不会发生任何事件。
以我有限的知识,我试图理解:
- 为什么会这样?
- 如何在事件之间的方法中间暂停而不冻结整个表单?
- 如何让每个事件出现在下一个事件之前,而不是在方法完成时发生所有事件?
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
}
解决方案
现在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()
了替换我以前调用鼠标和键盘事件的方法,但这与延迟问题无关。为我工作。
推荐阅读
- python - 从另一个类的方法动态创建 scipy.stats 分布
- python - 合并列中的类别
- html - Min-height:100vh 不适用于我的项目
- php - Symfony5连接拒绝使用docker连接到mysql
- c++ - 我想将 int 转换为 char 数组,其中 int 的 0-7 位是第一个 char 8-15 第二个等
- javascript - 响应式移动汉堡菜单
- github - 无法从 jupyterlab 将文件另存为 ipynb 文件
- javascript - 消息未定义
- javascript - 对 Postman 的响应,在纯 JS 中我得到:“错误:SyntaxError: Unexpected token < in JSON at position 0”
- html - HTML/CSS 列表项在左侧有太多空间