Friday, January 9, 2009

Is a specific app running?

How to know whether an app is running in REALbasic? The common idea is looping through all processes and testing with the name of the app which you want to know if it's opened.

Windows
On Windows, we can do it via declares, the Win32 APIs we need to use are EnumProcesses, EnumProcessModules, GetModuleFileNameEx, etc. I wrote a function a few days ago. You can find the source code of it in Window1 of the RB project attached. I didn't implemented it in a very smart way. It gets the names of all processes, then tests to see if a specific app name can be found. It because I wanted to demonstrate how to list the paths of all processes. You may make some changes on it to exit the For loop when the app is found.

Mac OS X
On Mac, calling AppleScript functions seems the best way. You can loop through all process objects provided by the System Events application in a tell block. However, since AppleScript supports using keyword each or plural of class name to access all objects in the direct parameter of tell statement (in this case, it's the System Events application), so that the script can be simply written like this:
on run {appname}
tell application "System Events"
if (name of each process) contains appname then
return true
else
return false
end if
end tell
end run
OR:
on run {appname}
tell application "System Events"
if (name of processes) contains appname then
return true
else
return false
end if
end tell
end run

On Leopard, AppleScript is updated to 2.0, many new features are introduced. As the result, it's able to test whether an app is running without launching it:
on run {appname}
if application appname is running then
return true
else
return false
end if
end run
The code above doesn't work on Tiger and earlier.

To use an AppleScript, drag and drop the scpt file to your project, and call it by its name showed in the listbox of project panel, as calling a global function. The AppleScript will be compiled and embedded to the app file you built. You will observe that the return value of any AppleScript you get in RB is a String, rather than the date type you expected. So you should compare it with "true" or "false", not a Boolean constant. Refer to the rbp I attached if my description isn't clear to you.

Attachment: IsProcRunning.zip

No comments:

Post a Comment