开发者

Can a Cocoa app's executable steal focus from caller?

开发者 https://www.devze.com 2023-02-11 06:43 出处:网络
Say I have a standard Cocoa Application call Foo.app (like the one you get just by choosing New Project > Cocoa Application in Xcode), if I open the app via a terminal using:

Say I have a standard Cocoa Application call Foo.app (like the one you get just by choosing New Project > Cocoa Application in Xcode), if I open the app via a terminal using:

open Foo.app/

Then I see Foo's name on the status bar up top and its window is in focus, in front of all other apps.

If instead I directly call from the terminal the executable buried in the .app folder, like:

Foo.app/Contents/MacOS/Foo

Nothing appears to happen. On inspection the app has indeed opened but it is not in focus (the terminal still is), I have开发者_运维问答 to find it on the dock or find its window.

Is there any way for the Foo application to make sure its in focus when its run? Even if its run via its executable as described above?


Your app can "steal focus" by calling

[[NSApplication sharedApplication] activateIgnoringOtherApps:YES];

See the NSApplication docs for more info.


did you mean to type:

open -a /Applications/Foo.app/

note the -a option


If you're asking how to give your app (that you're writing) this behavior -- within applicationWillFinishLaunching: you could call [NSApp activateIgnoringOtherApps:YES].


perhaps AppleScript?

tell application "TextEdit"
    activate
end tell


There are (at least) three different ways you open (and interact with) Applications from the Terminal.

  1. you can launch any Application (that is registered in LaunchServices) from the Terminal by typing open -a ApplicationName (note that you do not need the trailing ".app" or give any path)

  2. you can open an application giving its specific path by typing open /path/to/ApplicationName.app (you will rarely need that, given that the applications is likely already registered in LaunchServices)

  3. you can open and interact with the executable if you type open /path/to/ApplicationName.app/Contents/MacOS/ApplicationName. The difference here is that for some Applications, you can pass arguments or interact with them afterwards on your command line. Go ahead and try open /Applications/Mail.app/Contents/MacOS/Mail for example - it will give you a debugging log in return.

  4. you can interact with some applications even without using "open" by directly calling their executable; try /Applications/Firefox.app/Contents/MacOS/firefox-bin —help for example.

So if you do want to make sure the command-line-launched application is in focus, use either method 1 or 2.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号