macOS, is my app active?

Trevor DeVore lists at mangomultimedia.com
Sat Nov 23 09:06:55 EST 2019


On Sat, Nov 23, 2019 at 6:24 AM Klaus major-k via use-livecode <
use-livecode at lists.runrev.com> wrote:

> Hi friends,
>
> can we check if our standalone is currently active, means in
> the "foreground" or if it is not active? Know what I mean?
> If yes, how can we do that? LC? AppleScript?
>
> I want to alert the user if the app is active, but not if the app
> is not active.
>

Apple provides API calls to do this and wrapping Objective-C APIs is pretty
straightforward. The APIs you are interested in:

Get frontmost app:
https://developer.apple.com/documentation/appkit/nsworkspace/1532097-frontmostapplication?language=objc

Get bundle identifier of frontmost app:
https://developer.apple.com/documentation/appkit/nsrunningapplication/1529140-bundleidentifier?language=objc

I have a macOS LCB "playground" repo where I test a number of things out
and upload them for others to see. Take a look at
the NSWorkspaceGetFrontmostApplication function:

https://github.com/trevordevore/lc-macos-toolset/blob/master/NSWorkspace/nsworkspace.lcb#L133

You can call it like this:

```
put NSWorkspaceGetFrontmostApplication("bundle id")
```

If I run the function from within LiveCode it returns "com.runrev.livecode".

If I run the following in the message box and switch to Chrome it returns
"com.google.Chrome":

```
wait 1 second;put NSWorkspaceGetFrontmostApplication("bundle id")
```

So I would think it would do what you want. You would, however, need to
compile the nsworkspace.lcb and load the resulting extension in your app.
Here are some quick instructions in case you want to try:

1. Download and unzip repo using "Clone or Download" link found at
https://github.com/trevordevore/lc-macos-toolset
2. Launch LC 9 and open the Extension Builder (EB) from Tools > Extension
Builder menu.
3. Click on the folder icon in top right of EB window and select the
./NSWorkspace/nsworkspace.lcb file.
4. Click on play button in bottom left of EB window.
5. Test `wait 1 second;put NSWorkspaceGetFrontmostApplication("bundle id")`
in the message box. It should return a value.
6. Look in the ./NSWorkspace folder for the module.2.lcm file. This is the
file that can be renamed, added to your application folder, and loaded
using `load extension`.

Regarding step 6 - If you don't want to store your extension externally to
your application you can also use the "+" button in the EB to install the
extension in your LC environment. Now the extension will load whenever you
launch LC and you can select "NSWorkspace" in the Standalone Builder
Inclusions tab so that the extension is bundled with your executable.

-- 
Trevor DeVore
ScreenSteps
www.screensteps.com



More information about the use-livecode mailing list