Cocoa: Simulate Macbook upper keys & Multimedia keys

五迷三道 提交于 2019-11-30 14:02:09

问题


I am trying to simulate the upper Macbook keys to any active app using

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

So far I found and sent the first 4 key's events succesfully:

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

But I can't find any of the other key codes. I even iterate through 1000 integer sending its numbers as events, no one seems to work =P

So, is there any way to simulate these events?

Thank you


回答1:


Media keys are not treated as normal keyboard events, for some reason. This post shows what the events look like.




回答2:


As of 2017/2018 some of the APIs have changed. Try this snippet in 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)

(credit goes to @Alex293)

This is from our discussion on ways to programmatically control the keyboard brightness with: https://github.com/pirate/mac-keyboard-brightness

Also this SO answer: How to simulate mac media keys in cocoa



来源:https://stackoverflow.com/questions/10459085/cocoa-simulate-macbook-upper-keys-multimedia-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!