7

I have an app winth one window and one panel, attached to this window.

steps:

  1. deactivate my app (app opened, but without the focus)
  2. click on a button on panel (panel is focused now, but main window is not)

How to set focus to the main window (parent window) from the panel?

Bot
  • 11,868
  • 11
  • 75
  • 131
BUDDAx2
  • 399
  • 1
  • 4
  • 20
  • Is the main window a Cocoa main window? Is your application NSDocument-based? Do you mean key window status when you say focus? –  Feb 23 '11 at 10:40
  • 1
    When I say "to set focus", I mean "to activate" main window, set key window status. Application is always on top of the screen. And when I click somwhere outside the main window the application deactivating, but placed on top. – BUDDAx2 Feb 23 '11 at 13:12
  • Your answer with activateWithOptions: worked for me too. If you post it as an answer I'd be happy to upvote it :) – yuf Jun 07 '13 at 20:42
  • Make sure your panel responds YES to canBecomeKeyWindow – Nick Moore Jul 01 '13 at 15:04

2 Answers2

12

Swift 5 version of @BUDDAx2 answer:

NSApplication.shared.activate(ignoringOtherApps: true)
Starwave
  • 2,352
  • 2
  • 23
  • 30
10

It is not clear what you mean by focus, and whether what you call main window is a main window as defined in Cocoa. Assuming it is a Cocoa main window and focus is the same as key status,

[[NSApp mainWindow] makeKeyWindow];

or

[[NSApp mainWindow] makeKeyAndOrderFront:self];

If it is not a Cocoa main window, you need to have a reference to it and send it -makeKeyWindow or -makeKeyAndOrderFront:.

  • 1
    its not working. Maybe, because main window is NSFloatingWindowLevel? – BUDDAx2 Feb 23 '11 at 13:03
  • @BUDDAx2 Does the main window have a title bar or a resize bar? If you send `-canBecomeKeyWindow` to the main window, what is the return value? –  Feb 23 '11 at 23:43
  • -canBecomeKeyWindow returns true – BUDDAx2 Feb 28 '11 at 08:51
  • 3
    I understand what I need: [[NSRunningApplication currentApplication] activateWithOptions: NSApplicationActivateIgnoringOtherApps]; But I compiling my apps for 10.6 and 10.5. NSRunningApplication class is only in 10.6. How to do that in 10.5? – BUDDAx2 Feb 28 '11 at 14:45
  • I don't know why, but [NSApp deactivate]; do what I need :) – BUDDAx2 Feb 28 '11 at 15:29
  • 6
    `[[NSApplication sharedApplication] activateIgnoringOtherApps:YES]; // "Available in OS X v10.0 and later."` – superlukas Jul 01 '14 at 15:30