13

我正在尝试使用任何活动应用程序模拟上 Macbook 键

CGEventCreateKeyboardEvent (NULL, (CGKeyCode)keycode, true);
CGEventCreateKeyboardEvent (NULL, (CGKeyCode)keycode, false);

到目前为止,我成功地找到并发送了前 4 个键的事件:

keycode / Key

107 - Brightness Down
113 - Brightness Up
130 - Mission Control / Expose
160 - Dashboard / Launchpad
 ?? - Keyboard lit Down
 ?? - Keyboard lit Up
 ?? - Previous Track
 ?? - Play/Pause
 ?? - Next Track
 ?? - Mute
 ?? - Volume Down
 ?? - Volume Up
 ?? - Eject

但我找不到任何其他关键代码。我什至遍历了 1000 个整数,将其数字作为事件发送,似乎没有人工作 =P

那么,有没有办法模拟这些事件呢?

谢谢

4

2 回答 2

6

出于某种原因,媒体键不被视为正常的键盘事件。这篇文章显示了事件的样子。

于 2012-05-07T20:14:10.970 回答
2

截至 2017/2018 年,一些 API 发生了变化。在 Swift 中试试这个片段:

// Simulate illumination up
let code = NX_KEYTYPE_ILLUMINATION_UP
let event1 = NSEvent.otherEvent(with: .systemDefined, location: NSPoint.zero, modifierFlags: NSEventModifierFlags(rawValue: 0xa00), timestamp: 0, windowNumber: 0, context: nil, subtype: 8, data1: (Int((code << 16 as Int32) | (0xa << 8 as Int32))), data2: -1)
event1?.cgEvent?.post(tap: .cghidEventTap)
let event2 = NSEvent.otherEvent(with: .systemDefined, location: NSPoint.zero, modifierFlags: NSEventModifierFlags(rawValue: 0xb00), timestamp: 0, windowNumber: 0, context: nil, subtype: 8, data1: (Int((code << 16 as Int32) | (0xb << 8 as Int32))), data2: -1)
event2?.cgEvent?.post(tap: .cghidEventTap)



// Simulate illumination down
let code = NX_KEYTYPE_ILLUMINATION_DOWN
let event1 = NSEvent.otherEvent(with: .systemDefined, location: NSPoint.zero, modifierFlags: NSEventModifierFlags(rawValue: 0xa00), timestamp: 0, windowNumber: 0, context: nil, subtype: 8, data1: (Int((code << 16 as Int32) | (0xa << 8 as Int32))), data2: -1)
event1?.cgEvent?.post(tap: .cghidEventTap)
let event2 = NSEvent.otherEvent(with: .systemDefined, location: NSPoint.zero, modifierFlags: NSEventModifierFlags(rawValue: 0xb00), timestamp: 0, windowNumber: 0, context: nil, subtype: 8, data1: (Int((code << 16 as Int32) | (0xb << 8 as Int32))), data2: -1)
event2?.cgEvent?.post(tap: .cghidEventTap)

(归功于@Alex293

这是来自我们关于以编程方式控制键盘亮度的方法的讨论:https ://github.com/pirate/mac-keyboard-brightness

还有这个答案:如何在可可中模拟mac媒体键

于 2018-05-28T22:38:47.997 回答