Cocoa开关专注于应用程序,然后将其切换回来

时间:2012-11-13 19:50:55

标签: objective-c macos cocoa macos-carbon

我想创建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;
}

1 个答案:

答案 0 :(得分:7)

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

        _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