Cocoa: Simulate Macbook upper keys & Multimedia keys

后端 未结 2 797
别那么骄傲
别那么骄傲 2020-12-31 12:55

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

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


        
相关标签:
2条回答
  • 2020-12-31 13:22

    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

    0 讨论(0)
  • 2020-12-31 13:28

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

    0 讨论(0)
提交回复
热议问题