Last active
April 30, 2023 00:05
-
-
Save storoj/429e260f697594d42337843b3d523bf5 to your computer and use it in GitHub Desktop.
MacOS Media Key Press Emulation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@import CoreGraphics; | |
static const CGEventField kCGEventSubtype = 0x53; | |
static const CGEventField kCGEventData1 = 0x95; | |
static const CGEventField kCGEventData2 = 0x96; | |
static CGEventRef CGEventCreateMediaKeyEvent(CGEventSourceRef _Nullable source, int64_t key, BOOL down) { | |
CGEventFlags flags = (down ? NX_KEYDOWN : NX_KEYUP) << 8; | |
CGEventRef e = CGEventCreate(source); | |
CGEventSetType(e, NX_SYSDEFINED); | |
CGEventSetFlags(e, flags); | |
CGEventSetIntegerValueField(e, kCGEventSubtype, NX_SUBTYPE_AUX_CONTROL_BUTTONS); | |
CGEventSetIntegerValueField(e, kCGEventData1, flags | (key << 16)); | |
CGEventSetIntegerValueField(e, kCGEventData2, -1); | |
return e; | |
} | |
static void PostKey(CGEventSourceRef _Nullable source, uint64_t key) { | |
{ | |
CGEventRef e = CGEventCreateMediaKeyEvent(source, key, YES); | |
CGEventPost(kCGHIDEventTap, e); | |
CFRelease(e); | |
} | |
{ | |
CGEventRef e = CGEventCreateMediaKeyEvent(source, key, NO); | |
CGEventPost(kCGHIDEventTap, e); | |
CFRelease(e); | |
} | |
} | |
int main(int argc, const char * argv[]) { | |
CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateHIDSystemState); | |
PostKey(source, NX_KEYTYPE_SOUND_UP); | |
CFRelease(source); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment