【问题标题】:OSX keyboard shortcut background application, how toOSX键盘快捷键后台应用程序,如何
【发布时间】:2011-01-09 13:08:27
【问题描述】:

我希望我的 OSX 应用程序位于后台并等待键盘快捷键生效。它应该可以像偏好设置中的 Growl 一样进行配置,或者可以作为状态栏中的 Dropbox 访问。

  • 我必须使用什么样的 xcode 模板?
  • 如何全局捕获键盘快捷键?

【问题讨论】:

    标签: macos keyboard-shortcuts backgroundworker


    【解决方案1】:

    在 GitHub 上查看 Dave DeLong 的 DDHotKey 课程。

    DDHotKey 是一个易于使用的 Cocoa 类,用于注册应用程序以响应系统键事件或“热键”。

    全局热键是始终执行特定操作的组合键,无论哪个应用程序位于最前面。例如,“command-space”的 Mac OS X 默认热键显示 Spotlight 搜索栏,即使 Finder 不是最前面的应用程序。

    也是一个慷慨的许可证。

    【讨论】:

      【解决方案2】:

      如果您想在首选项中访问它,请使用首选项窗格模板。如果你想在状态栏中,创建一个普通的应用程序,在Info.plist中将LSUIElement键设置为1,并使用NSStatusItem创建项目。

      要全局捕获快捷方式,您还需要包含 Carbon 框架。使用RegisterEventHotKeyUnregisterEventHotKey 注册活动。

      OSStatus HotKeyEventHandlerProc(EventHandlerCallRef inCallRef, EventRef ev, void* inUserData) {
          OSStatus err = noErr;
          if(GetEventKind(ev) == kEventHotKeyPressed) {
              [(id)inUserData handleKeyPress];
          } else if(GetEventKind(ev) == kEventHotKeyReleased) {
              [(id)inUserData handleKeyRelease];
          } else err = eventNotHandledErr;
          return err;
      }
      
      //EventHotKeyRef hotKey; instance variable
      
      - (void)installEventHandler {
          static BOOL installed = NO;
          if(installed) return;
          installed = YES;
          const EventTypeSpec hotKeyEvents[] = {{kEventClassKeyboard,kEventHotKeyPressed},{kEventClassKeyboard,kEventHotKeyReleased}};
          InstallApplicationEventHandler(NewEventHandlerUPP(HotKeyEventHandlerProc),GetEventTypeCount(hotKeyEvents),hotKeyEvents,(void*)self,NULL);
      }
      
      - (void)registerHotKey {
          [self installEventHandler];
          UInt32 virtualKeyCode = ?; //The virtual key code for the key
          UInt32 modifiers = cmdKey|shiftKey|optionKey|controlKey; //remove the modifiers you don't want
          EventHotKeyID eventID = {'abcd','1234'}; //These can be any 4 character codes. It can be used to identify which key was pressed
          RegisterEventHotKey(virtualKeyCode,modifiers,eventID,GetApplicationEventTarget(),0,(EventHotKeyRef*)&hotKey);
      }
      - (void)unregisterHotKey {
          if(hotkey) UnregisterEventHotKey(hotKey);
          hotKey = 0;
      }
      
      - (void)handleHotKeyPress {
          //handle key press
      }
      - (void)handleHotKeyRelease {
          //handle key release
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-04
        • 2012-08-10
        • 2011-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多