使用事件点击无法在某些应用程序上模拟退格按钮 [英] Can't simulate backspace button on some applications with event tap

查看:98
本文介绍了使用事件点击无法在某些应用程序上模拟退格按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Mac OS上模拟某些按键.如果按下'h'键(例如,如果用户键入'tigh',它将变成'ti'),则该代码应通过修改键盘事件来删除前一个字符.但是,它仅适用于某些应用程序.其他人完全拒绝我的活动.这段代码有什么问题吗?

I'm trying to simulate some key presses on Mac OS. This code is supposed to delete one previous character if the 'h' key is pressed (e.g. if user types 'tigh' it will become 'ti') by modifying keyboard events. However it only works with some applications; others totally refuse my events. Is there any problem with this code ?

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    CFMachPortRef      eventTap;
    CGEventMask        eventMask;
    CFRunLoopSourceRef runLoopSource;

    eventMask = ((1 << kCGEventKeyDown) | (1 << kCGEventKeyUp));

    eventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0,
                                eventMask, KeyHandler, NULL);
    if (!eventTap) {
        fprintf(stderr, "failed to create event tap\n");
        exit(1);
    }

    runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0);
    CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes);    
    CGEventTapEnable(eventTap, true);
    CFRunLoopRun();
}

CGEventRef KeyHandler(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon)
{
    UniCharCount actualStringLength;
    UniCharCount maxStringLength = 1;    
    UniChar chars[3];

    CGEventKeyboardGetUnicodeString(event, maxStringLength, &actualStringLength, chars);

    if (chars[0] == 'h') {
        chars[0] = '\b';
        CGEventKeyboardSetUnicodeString(event, 1, chars);
        return event;        
    }

    return event;
}

推荐答案

某些应用程序根据事件(CGEventGetIntegerValueField(event, kCGKeyboardEventKeycode))的键代码而不是事件的UnicodeString来查找要键入的内容.

Some applications find what is being typed based on the key code from the event (CGEventGetIntegerValueField(event, kCGKeyboardEventKeycode)), rather than the event's UnicodeString.

也就是说,您需要将事件的kCGKeyboardEventKeycode值从"h"提供的 4 更新为 51 或( 0x33 )退格.

That is, you will need to update the event's kCGKeyboardEventKeycode value from the 4 supplied by "h" to 51 or (0x33) for Backspace.

这篇关于使用事件点击无法在某些应用程序上模拟退格按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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