在OS X中以编程方式模拟/切换CAPS LOCK [英] Simulate/Toggle CAPS LOCK programatically in OS X

查看:104
本文介绍了在OS X中以编程方式模拟/切换CAPS LOCK的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到很多关于该主题的文章.但是在任何地方都没有找到明确的答案.

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

有没有办法在Objective-C或C代码中切换CAPS LOCK?我不是在寻找使用X11库的解决方案.我不担心LED的开/关状态.但是只是CAPS LOCK的功能(更改字母的大小写并在数字键上打印特殊字符).

Is there a way to toggle CAPS LOCK in Objective-C or C code? I am not looking for a solution using X11 libs. I am not bothered about the LED on/off status. But just the functionality of CAPS LOCK (changing the case of letters and printing the special characters on number keys).

为什么CGEvent不支持其他键呢?

Why is CGEvent not supporting this the way it does for other keys?

推荐答案

经过长时间的奋斗,我做到了这一点.

I got this working, after a long struggle.

调用下面给出的方法两次.一次是向上事件,另一个是向下事件.例如,为了模拟CAPS A,我们需要执行以下操作.

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是'a'的键控代码.

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);
    }
}

这篇关于在OS X中以编程方式模拟/切换CAPS LOCK的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆