I’m trying to capture keystrokes and replay them afterwards as equal as possible (time critical).
What I tried so far:
First capture keys using SetWindowsHookEx (with WH_KEYBOARD_LL) and remember scan code and timestamp (milliseconds precision)
Then converting that raw data to predefined function calls (C#) after capture.
These are KeyUp and KeyDown methods implemented using SendInput with the known scan code (KEYEVENTF_SCANCODE in KEYBDINPUT struct)
I have concerns about the waiting part between these calls, though. Currently I’m using Thread.Sleep (single threaded replay application), but heard that would not be very precisely.
As I’m still asking here you’ll imagine that the current replay is not as exact as needed. It differs the same each time though!
Could I measure the overhead of my program (or of the single functions) and substract that each wait?
Should I try a different approach? Or is there a problem somewhere else in my thoughts?
(the program doesn’t need to be portable and can be tuned just for the dev computer)
Instead of using Thread.Sleep use a very tight loop and just continually check the time difference. You could even make it somewhat smart that for anything under a second, you just run in the tight loop and anything over a second you thread.sleep for 750ms and then check the difference and keep doing that until it is under a second.
Maybe something like this, a class to hold your work items:
Then use it like this:
It’s not perfect because there is time between when the while loop breaks and the debug fires, but it should get you pretty close. Some of the comments also had links that might be valuable (i.e. using a WaitOne or the parallel tasks)