1

I'm writing a multi-document application using Cocoa. The user must enter a password when opening a document. After a certain amount of time without activities on a document the user is once again required to enter the password.

Right now I'm using NSAplication's beginSheet:modalForWindow:modalDelegate:didEndSelector:contextInfo: to show the password prompt in a custom sheet. While it works it has the unfortunate side-effect of the window being brought to front and given focus even if another document is being worked on at the time. It is only problematic if my application is in front.

Is there a way to prevent opening a sheet from snatching focus if its parent window is not active?

Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
ims
  • 66
  • 6

1 Answers1

0

There isn't a simple way. The hacky way would be to make a subclass of NSWindow for both the document's window and the sheet's window, and in that class, override both orderFront: and makeKeyWindow to do nothing during the time you call beginSheet. For example,

In the NSWindow subclass:

-(void)awakeFromNib
{
    hack = NO;
}

-(void)hackOnHackOff:(BOOL)foo
{
    hack = foo;
}

- (void)orderFront:(id)sender
{
    if (!hack)
        [super orderFront:sender];
}

- (void)makeKeyWindow
{
    if (!hack)
        [super makeKeyWindow];
}

And then your beginSheet call would look like:

-(void)sheet
{
    SpecialSheetWindow* documentWindow = [self windowForSheet];
    [documentWindow hackOnHackOff:YES];
    [sheetWindow hackOnHackOff:YES];
    [[NSApplication sharedApplication] beginSheet:sheetWindow
                       modalForWindow:documentWindow 
                       modalDelegate:self  didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:) contextInfo:nil];
    [documentWindow hackOnHackOff:NO];
    [sheetWindow hackOnHackOff:NO];
}
Ken Aspeslagh
  • 11,484
  • 2
  • 36
  • 42
  • Yes, that would indeed be a hack and I rather avoid going this route. I think I'll use a combination of Ken T.'s proposal to only show the sheet when the window becomes key and a visual cue to the user (maybe a half-transparent overlay). Thank you both a lot! – ims May 21 '12 at 02:55