ahmet2106
ahmet2106

Reputation: 5007

How to order a window to front if you are not in the Application in Objective-C

Is there a way to make a "makeKeyAndOrderToFront" without beeing in the Application?

If I am in Safari and in the Menu Bar there is a MenuItem to my App, after I press this, i want to show a window of my App in the Front (makeKeyAndOrderToFront makes this just if you are in the Application).

Which way can I use? And how can I animate this Window (like Tweeties Add new Tweet -> atebits.com).

Thank you!

Upvotes: 9

Views: 5954

Answers (5)

kittonian
kittonian

Reputation: 1431

Just an update if anyone needs a solution for Swift vs ObjC:

NSApp.activate(ignoringOtherApps: true)

Upvotes: 1

Jeremy W. Sherman
Jeremy W. Sherman

Reputation: 36143

Provided your application has a connection to the window server (which it will if it's using AppKit or Carbon), you can use the Core Services function SetFrontProcess() to bring it to the fore. SetFrontProcessWithOptions() can be used to bring only the frontmost non-floating window of your app to the fore. These functions appear to be available to 64-bit applications, but if you're targeting 10.6+, you're likely better off using the NSRunningApplication class. Something like

[[[NSRunningApplication
   runningApplicationsWithBundleIdentifier:ident] lastObject]
 activateWithOptions:0]

should do the trick.

Upvotes: 0

Matt Stevens
Matt Stevens

Reputation: 13343

As you've discovered, changing the window order within your application does not have any impact on which application is active. You can bring your application to the foreground by activating it:

[NSApp activateIgnoringOtherApps:YES];

If your application had a dock icon the behavior would be similar to the user clicking on it.

Upvotes: 22

kubi
kubi

Reputation: 49364

Applescript would be a trivially easy way to make your app frontmost. It won't be doing any animation, though.

tell application "System Events" to set frontmost of process "My Application" to true

Upvotes: 1

ericg
ericg

Reputation: 8722

Perhaps the best way to accomplish what you want, if I understand the question correctly, is to have your application respond to an Apple event which you send to it after your menu item is selected which will bring your application and desired window to the front.

Upvotes: 0

Related Questions