Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocoa: Simulate Macbook upper keys & Multimedia keys

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

like image 609
Rodrigo Avatar asked May 05 '12 05:05

Rodrigo


2 Answers

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

like image 164
LaC Avatar answered Nov 04 '22 14:11

LaC


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

like image 40
Nick Sweeting Avatar answered Nov 04 '22 14:11

Nick Sweeting