【问题标题】:How to intercept music control keyboard shortcuts in Java?如何在 Java 中拦截音乐控制键盘快捷键?
【发布时间】:2016-08-12 06:58:53
【问题描述】:

如果您的键盘上有播放/暂停/等按钮(音乐控制快捷键),并且您按下它们,iTunes 将打开(至少在 Mac 上)。

如果你最近打开了另一个音乐播放器,比如 Spotify,它实际上会拦截快捷键,而 iTunes 不会做任何事情。

嗯,我想用 Java 制作一个音乐播放器,我也想有同样的行为。我希望我的应用程序能够拦截此类快捷方式,并且其他程序不应干扰。

我正在使用 JavaFX,尽管我认为这并不重要。

我怎样才能做到这一点?

我已经能够检测到用户使用JNativeHook 按下的键,但我不知道如何拦截这些键,以便其他应用程序不会使用它们。

【问题讨论】:

标签: java keyboard keyboard-shortcuts keyboard-events


【解决方案1】:

一旦检测到按键,您可以发送暂停键,以便暂停正在播放的 iTunes 歌曲,您可以使用boolean 变量来检测在键盘上键入或发送的快捷键之间程序(以备不时之需)

或

您可以使用一些 c 代码(将 c 程序与您的 java 程序一起启动)看看@Dave Delongs 在这里的回答 Modify NSEvent to send a different key than the one that was pressed 如果您需要键码Where can I find a list of Mac virtual key codes?

例如,如果您的音乐程序使用p to play songs 和r to listen to the next song,iTunes 使用spacebar 播放歌曲并使用right arrow key 转到下一首,您可以修改@Dave Delongs 答案这里是更改:-

#import <Cocoa/Cocoa.h>

CGEventRef myCGEventCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon) {

//0x31 is the virtual keycode for "Spacebar"
//0x23 is the virtual keycode for "p"
  if (CGEventGetIntegerValueField(event, kCGKeyboardEventKeycode) == 0x31) {
    CGEventSetIntegerValueField(event, kCGKeyboardEventKeycode, 0x23);
  }

//0x7C is the virtual keycode for "Right arrow"
//0x0F is the virtual keycode for "R"
  if (CGEventGetIntegerValueField(event, kCGKeyboardEventKeycode) == 0x7C) {
    CGEventSetIntegerValueField(event, kCGKeyboardEventKeycode, 0x0F);
  }

  return event;
}

int main(int argc, char *argv[]) {
  NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  CFRunLoopSourceRef runLoopSource;

  CFMachPortRef eventTap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault, kCGEventMaskForAllEvents, myCGEventCallback, NULL);

  if (!eventTap) {
    NSLog(@"Couldn't create event tap!");
    exit(1);
  }

  runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0);

  CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes);

  CGEventTapEnable(eventTap, true);

  CFRunLoopRun();

  CFRelease(eventTap);
  CFRelease(runLoopSource);
  [pool release];

  exit(0);
}

【讨论】:

    【解决方案2】:

    您也许可以使用iTunesPatch 中的一些代码来完成您要查找的内容,但似乎系统守护程序可能需要在安装时进行修改,您可能必须使用 Objective- C/斯威夫特。

    在博文here 中有更多关于 iTunesPatch 的详细信息。

    【讨论】:

      猜你喜欢
      • 2011-04-08
      • 1970-01-01
      • 2014-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-20
      • 1970-01-01
      相关资源
      最近更新 更多