Reputation: 3
I'm attempting to write a Windows Form App that sends different keys to the active window after certain (non-regular) time intervals.
For example, after pressing a button, the program will wait 3 seconds, then send an "H" to the active window. After 1 more second, it sends an "E", and after another second, it sends a "Y".
But when I try this:
Thread.Sleep(3000);
SendKeys.Send("H");
Thread.Sleep(1000);
SendKeys.Send("E");
Thread.Sleep(1000);
SendKeys.Send("Y");
the program waits (at least) 3 seconds, but does not seem to pause between the next two keys sent.
I've been trying to implement something similar using a Timer since Sleep only guarantees a delay at least as long the argument given, and I need something more precise. However, the only examples I've been able to find had code executing after a regular time interval.
Is there a way to use a Timer to accomplish what I tried using Sleep, or a better method in general?
Upvotes: 0
Views: 1689
Reputation: 14532
Use SendWait instead of Send.
Thread.Sleep(3000);
SendKeys.SendWait("H");
Thread.Sleep(1000);
SendKeys.SendWait("E");
Thread.Sleep(1000);
SendKeys.SendWait("Y");
Upvotes: 1
Reputation: 9858
Your button event handler and your Thread.Sleep calls are happening on the same thread. Your form cant begin to handle the keys it received until your OnClick handler ends.
In your Click handler:
Thread t = new Thread(new ThreadStart(sendTheKeys));
t.start();
And then a method to send the keys,
private void sendTheKeys()
{
Thread.Sleep(3000);
this.Invoke(new MethodInvoker(()=> {SendKeys.Send('H');}));
Thread.Sleep(1000);
this.Invoke(new MethodInvoker(()=>{SendKeys.Send("E");}));
Thread.Sleep(1000);
this.Invoke(new MethodInvoker(() => {SendKeys.Send("Y");}));
}
Something like that should get you started. I did this off the top of my head and may have forgotten the nitty gritting of the Thread Start code
Upvotes: 0