可可将焦点切换到应用程序,然后再切换回 [英] Cocoa switch focus to application and then switch it back

查看:81
本文介绍了可可将焦点切换到应用程序,然后再切换回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to create OS X application which shows up and getting focused with system-wide hotkey, and then, with same hotkey it should dissapear and switch focus back. Just like Alfred does it.

问题是我无法集中精力使用以前使用的应用程序.回到焦点意味着我不能继续输入以前的应用程序.

The problem is that I can't focus back on application previously used. By focusing back I mean that I can't continue typing in previous app.

这是我的热键处理程序:

Here is my hotkey handler:

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

推荐答案

在两种情况下都可以激活...您应该将其禁用.在激活之前,保存旧的活动应用程序

well activate in both cases... you should deactivate. BEFORE you activate, save old active app

        _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

这篇关于可可将焦点切换到应用程序,然后再切换回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆