In Lion, I want to start an application and wait for its window to actually open on the screen.
I know that I can start the application (arbitrarily called “TheApplication”) and wait for the existence of its process (arbitrarily called “TheProcess”), as follows:
tell application "TheApplication" to activate
tell application "System Events"
set theProc to a reference to process "TheProcess"
repeat until exists theProc
end repeat
end tell
However, there is no guarantee that the application’s window will actually be open after the process’s existence is detected.
I need to wait for this window opening, because I want to programmatically switch to a new space after the window is showing on the screen. If I perform the space switch too soon, the window could open in the new space, which is not my intent.
I know that I could just wait for an arbitrary amount of time, during which I can assume that the window has probably opened. However, that is not definitive. Is there any kind of test I can perform or event that I can wait for which I can count on to tell me when an arbitrary application’s window is actually showing on the screen?
If the only way to do this is within Cocoa, I’m happy to do so as part of an ASOC application.
Thanks in advance for your suggestions.