Prevent custom sheet from snatching focus

217 Views Asked by At

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?

1

There are 1 best solutions below

1
On

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];
}