9

我想创建 OS X 应用程序,它显示并使用系统范围的热键获得焦点,然后,使用相同的热键它应该消失并切换焦点。就像阿尔弗雷德一样。

问题是我无法专注于以前使用的应用程序。通过专注于我的意思是我不能继续在以前的应用程序中输入。

这是我的热键处理程序:

OSStatus OnHotKeyEvent(EventHandlerCallRef nextHandler,EventRef theEvent, void *userData)
{
    AppDelegate *me = (__bridge AppDelegate*) userData;

    EventHotKeyID hkCom;

    GetEventParameter(theEvent, kEventParamDirectObject, typeEventHotKeyID, NULL, sizeof(hkCom), NULL, &hkCom);

    if([[me window] isVisible]) {
        [[NSApplication sharedApplication] activateIgnoringOtherApps:NO];
        [[me window] orderOut:NULL];
    }
    else {
        [[NSApplication sharedApplication] activateIgnoringOtherApps:YES];
        [[me window] makeKeyAndOrderFront:nil];

    }

    return noErr;
}
4

1 回答 1

9

在这两种情况下都很好激活......你应该停用。在您激活之前,请保存旧的活动应用程序

        _oldApp = [[NSWorkspace sharedWorkspace] frontmostApplication];

稍后激活

        [_oldApp activateWithOptions:NSApplicationActivateIgnoringOtherApps];

--- 完整来源

@implementation DDAppDelegate {
    NSStatusItem *_item;
    NSRunningApplication *_oldApp;
}

- (void)applicationWillFinishLaunching:(NSNotification *)notification {
    NSLog(@"%@", [[NSWorkspace sharedWorkspace] frontmostApplication].bundleIdentifier);

    _item = [[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength];
    _item.title = @"TEST";
    _item.target = self;
    _item.action = @selector(toggle:);
}

- (void)applicationWillBecomeActive:(NSNotification *)notification {
    NSLog(@"%@", [[NSWorkspace sharedWorkspace] frontmostApplication].bundleIdentifier);
}

//---

- (IBAction)toggle:(id)sender {
    if(!_oldApp) {
        NSLog(@"%@", [[NSWorkspace sharedWorkspace] frontmostApplication].bundleIdentifier);
        _oldApp = [[NSWorkspace sharedWorkspace] frontmostApplication];
        [NSApp activateIgnoringOtherApps:YES];
    }
    else {
        [_oldApp activateWithOptions:NSApplicationActivateIgnoringOtherApps];
        _oldApp = nil;
    }
}
@end
于 2012-11-13T19:59:32.177 回答