The SendKeys
method is a last-ditch effort for attempting to automate old programs that don't have any programmatic access. Per its documentation,
Use the SendKeys method to send keystrokes to applications that have no automation interface.
If you're trying to automate a web browser (as might be done in some sort of automated testing), you should use a library designed for automating a web browser. For example, Internet Explorer has a substantial COM Automation interface (see its documentation, though I don't see as many samples using VBScript on MSDN as I used to, as I suspect they want people to move to .NET and PowerShell for this sort of thing). Using an actual object library for the browser you're automating should allow you to directly control it and handle events, such as your desire to do something when a browser window is closed.
If you're just trying to load the data on a web page, rather than relying on a web browser, you can just load the data using the WinHttpRequest object.
If you do in fact need to use SendKeys
to automate something, or otherwise want to find a way to stop your script at certain times, the best way is to have your script check to see if it should continue to run before it continues. For example, after your Sleep
call, it should check that whatever it's automating is in the state it's expecting. There's not a lot one can check using just VBScript without loading a COM object that supports a more comprehensive interface, but you can get a little use out of running WScript.AppActivate
and checking its return value to see if a window you're looking for is still there. If your script determines that it should terminate, it can call the WScript.Quit
method to do so.