Can a Cocoa app's executable steal focus from caller?
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.
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)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)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 tryopen /Applications/Mail.app/Contents/MacOS/Mail
for example - it will give you a debugging log in return.- 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.
精彩评论