Created
January 16, 2020 03:00
-
-
Save linrock/436ec64e6636b4fb5621999d22f9e087 to your computer and use it in GitHub Desktop.
Programmatically check if caps lock is on in macOS using C++
This file contains 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
#include <IOKit/IOKitLib.h> | |
#include <IOKit/hidsystem/IOHIDLib.h> | |
#include <IOKit/hidsystem/IOHIDParameter.h> | |
#include <CoreFoundation/CoreFoundation.h> | |
// Prints 0 if capslock is off. Prints 1 if capslock is on | |
// Modified from: https://discussions.apple.com/thread/7094207 | |
// Compile with: | |
// clang -framework IOKit -framework CoreFoundation -o capslock capslock.cpp | |
int main(int argc, char **argv) { | |
kern_return_t kr; | |
io_service_t ios; | |
io_connect_t ioc; | |
CFMutableDictionaryRef mdict; | |
mdict = IOServiceMatching(kIOHIDSystemClass); | |
ios = IOServiceGetMatchingService(kIOMasterPortDefault, (CFDictionaryRef) mdict); | |
if (!ios) { | |
if (mdict) { | |
CFRelease(mdict); | |
} | |
fprintf(stderr, "IOServiceGetMatchingService() failed\n"); | |
return 1; | |
} | |
kr = IOServiceOpen(ios, mach_task_self(), kIOHIDParamConnectType, &ioc); | |
IOObjectRelease(ios); | |
if (kr != KERN_SUCCESS) { | |
fprintf(stderr, "IOServiceOpen() failed: %x\n", kr); | |
return (int) kr; | |
} | |
// CAPSLOCK_QUERY | |
bool state; | |
kr = IOHIDGetModifierLockState(ioc, kIOHIDCapsLockState, &state); | |
if (kr != KERN_SUCCESS) { | |
IOServiceClose(ioc); | |
fprintf(stderr, "IOHIDGetModifierLockState() failed: %x\n", kr); | |
return (int) kr; | |
} | |
IOServiceClose(ioc); | |
fprintf(stdout, "%d\n", (int) state); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment