Question

I need to set a delay on the SendKeys.Send in my code. How can this be done?

case "Open Google Chrome":
System.Diagnostics.Process.Start(@"C:\Program Files\Google\Chrome\Application\chrome.exe");
SendKeys.Send("{ENTER}");
break;

Why do I need this? Due to my system being slow Google Chrome takes about 10 seconds to start up so essentially I need the delay for the Sendkeys to be set to 10 seconds because I want the key pressed after Google Chrome has loaded up.

An example would be appreciated. Thanks.

Was it helpful?

Solution

Just sleep in between the two actions.

System.Diagnostics.Process.Start(@"C:\Program Files\Google\Chrome\Application");
System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10));
SendKeys.Send("{ENTER}");

OTHER TIPS

A simple Google search would have turned up:

System.Threading.Thread.Sleep(10000);

But keep in mind that a far better approach would be to loop each second, checking if Chrome had actually started since this will better handle situations where:

  1. Chrome startup suddenly gets faster (you won't then wait unnecessarily).
  2. Chrome takes 11 seconds to start one day (your ten-second-delay script fails miserably).

You can use Thread.Sleep(10 * 1000); but this will make current thread to sleep for 10seconds. If you dont want to make Current Thread to sleep I will suggest you to use a Timer

var timer = new System.Threading.Timer((x) =>
{
    SendKeys.Send("{ENTER}");
}, null, 10000, Timeout.Infinite);

This will be executed in ThreadPool thread preventing your current thread from blocking.

Thread.Sleep(10000)

http://msdn.microsoft.com/en-us/library/d00bd51t.aspx

(EDIT: removed CurrentThread reference as correctly pointed out in comments)

Just use

Thread.sleep(10000) 
SendKeys.Send("{ENTER}";

You use the 10000 because it is in milliseconds

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top