skip down to the 3 comments

Using Cocoa to keep an app window always on top

Sometimes you want your application to keep one of it’s windows always-on-top. A chat application like Adium for example, allows you to keep your conversation window always-on-top so you can follow the conversation whilst still using other applications. In the TellyBox application I wrote, this functionality is also very useful, as you can watch tv whilst still working in other applications.

So the basic implementation was fairly simple. You just use the windowDidResignMain notification, and then re-set the window level a more fitting one. Below I have also wrapped around a preference setting:

- (void)windowDidResignMain:(NSNotification *)notification
{
  // It's always nicer if the user has a choice
  if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultAlwaysOnTop"] == YES) {
    [[self window] setLevel:NSFloatingWindowLevel];
  } else {
    [[self window] setLevel:NSNormalWindowLevel];
  }
}

My TellyBox application allows you to go fullscreen via the existing Flash application embedded in a webkit view. Using just the basic implementation meant that when going into fullscreen mode the frame of the original window remained in view. To fix this I added this extra bit of code, which gets used via the firing of another useful notification windowDidBecomeMain :

- (void)windowDidBecomeMain:(NSNotification *)notification
{
  [[self window] setLevel:NSNormalWindowLevel];
}

which sets the window level back to it’s default value of 0 when it becomes the main window i.e when you select it.

I hope this little snippet helps people trying to achieve the same effect in their apps.

There have been 3 responses to this post.

  1. Heinz

    Do you have an idea, why this doesn’t work here on my machine? It could be Snow Leopard?

  2. newbie

    Hi,

    Ok maybe this should be obvious, but I’m getting started with xcode. Where exactly do I put this to make my window floating?

    another thing that is hurting my contemplation is I’m trying to use applescriptobjc.

  3. The Dude

    Thank you so much for this!


back to the top