I am developing an application (sort of a game helper), which sends keystrokes to a game at certain time intervals (you can specify what key will be pressed).
The problem is that I need to do the KeyPress event with a millisecond precision. After some research I found out that Thread.Sleep has a resolution of 20-50 ms and the best I could find so far was using the StopWatch() like following:
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;
});
As duration of KeyPress event varies within 0.3 - 1.5 ms I also keep track of that in order to get rid of deviation.
Nonetheless, I am only able to get 60% accuracy with this code, as even the StopWatch() is not that precise (of course if my code is not incorrect).
I would like to know, how can I achieve at least 90% accuracy?
You could try using ElapsedTicks. It is the smallest unit that the Stopwatch can measure and you can convert the number of elapsed ticks to seconds (and fractions of seconds of course) using the
Frequency
property. I do not know if it is better thanElapsed.TotalMilliseconds
but worth a try.