Simulate/Toggle CAPS LOCK programatically in OS X

后端 未结 2 1385
自闭症患者
自闭症患者 2020-12-11 10:53

I have seen many post on this topic. But haven\'t found a clear answer anywhere.

Is there a way to toggle CAPS LOCK in Objective-C or C code? I am not looking for a

相关标签:
2条回答
  • 2020-12-11 11:36

    I got this working, after a long struggle.

    Invoke the method given below twice. Once for up event and another for down event. For example for simulating CAPS A, we need to do the following.

    [self handleKeyEventWithCapsOn:0 andKeyDown:NO];
    [self handleKeyEventWithCapsOn:0 andKeyDown:YES];
    

    0 is the keycode for 'a'.

    - (void) handleKeyEventWithCapsOn:(int) keyCode andKeyDown:(BOOL)keyDown
    {
        if(keyDown)
        {
            CGEventRef eventDown;
            eventDown = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)keyCode, true);
            CGEventSetFlags(eventDown, kCGEventFlagMaskShift);
            CGEventPost(kCGSessionEventTap, eventDown);
            CFRelease(eventDown);
        }
        else
        {
            CGEventRef eventUp;
            eventUp = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)keyCode, false);
            CGEventSetFlags(eventUp, kCGEventFlagMaskShift);
            CGEventPost(kCGSessionEventTap, eventUp);
    
            // SHIFT Up Event
            CGEventRef eShiftUp = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)56, false);
            CGEventPost(kCGSessionEventTap, eShiftUp);
            CFRelease(eventUp);
            CFRelease(eShiftUp);
        }
    }
    
    0 讨论(0)
  • 2020-12-11 11:52
    var ioConnect: io_connect_t = .init(0)
    let ioService = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching(kIOHIDSystemClass))
    IOServiceOpen(ioService, mach_task_self_, UInt32(kIOHIDParamConnectType), &ioConnect)
    
    var modifierLockState = false
    IOHIDGetModifierLockState(ioConnect, Int32(kIOHIDCapsLockState), &modifierLockState) 
    
    modifierLockState.toggle()
    IOHIDSetModifierLockState(ioConnect, Int32(kIOHIDCapsLockState), modifierLockState)
    
    IOServiceClose(ioConnect)
    
    0 讨论(0)
提交回复
热议问题