【发布时间】:2015-09-13 12:34:48
【问题描述】:
我正在开发一个应用程序(类似于游戏助手),它以特定的时间间隔向游戏发送击键(您可以指定要按下的键)。
问题是我需要以毫秒精度执行 KeyPress 事件。经过一番研究,我发现 Thread.Sleep 的分辨率为 20-50 毫秒,到目前为止我能找到的最好的方法是使用 StopWatch(),如下所示:
cmd_PlayJumps = new DelegateCommand(
() =>
{
ActivateWindow();
Stopwatch _timer = new Stopwatch();
Stopwatch sw = new Stopwatch();
double dElapsed = 0;
//Initial Key Press
_timer.Start();
_Keyboard.KeyPress(WindowsInput.Native.VirtualKeyCode.RETURN);
int iTotalJumps = SelectedLayout.JumpCollection.Count;
//loop through collection
for (int iJump = 0; iJump < iTotalJumps - 1; iJump++)
{
dElapsed = _timer.Elapsed.TotalMilliseconds;
sw.Restart();
while (sw.Elapsed.TotalMilliseconds < SelectedLayout.JumpCollection[iJump + 1].WaitTime -
dElapsed)
{
//wait
}
_timer.Restart();
_Keyboard.KeyPress(WindowsInput.Native.VirtualKeyCode.RETURN);
}
//final key press
_Keyboard.KeyPress(WindowsInput.Native.VirtualKeyCode.RETURN);
_timer.Stop();
_timer = null;
});
由于 KeyPress 事件的持续时间在 0.3 - 1.5 毫秒内变化,我也会跟踪它以消除偏差。
尽管如此,我只能用这段代码获得 60% 的准确度,因为即使是 StopWatch() 也不是那么精确(当然,如果我的代码不正确的话)。
我想知道,我怎样才能达到至少 90% 的准确率?
【问题讨论】:
-
问题是你需要幸运,这完全取决于到达 .Tick 的频率,取决于你的硬件,大约为 0.2-2 毫秒。避免这种情况非常困难,您可以尝试设置高进程优先级以窃取 CPU 以获取更多 Ticks。
-
还可以尝试设置
while (sw.Elapsed.TotalMilliseconds <= SelectedLayout.JumpCollection[iJump + 1].WaitTime - dElapsed),这有时会为您节省另一个时间并提高一点准确性 -
*another comment (sry for overposting):设置优先级(如前所述):
System.Diagnostics.Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High; -
@Johan 为什么不发布这些 cmets 作为答案?
-
@user1666620 好的,会的:)