如何使用Objective C按下键盘键? [英] How can I press a keyboard key using Objective C?

查看:101
本文介绍了如何使用Objective C按下键盘键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望允许我的应用程序执行某些操作,例如,按Enter键或键入单词而无需实际触摸这些键.这可能吗?我该如何制作一个屏幕键盘,让您键入不同的应用程序?

I want to allow my application to do things like hit the enter key or type words without actually touching the keys. Is this possible? How could I make an onscreen keyboard that lets you type into different applications?

推荐答案

关于如何创建屏幕键盘"的问题非常广泛,因为有许多有效的方法可以解决这一问题,而不是一种单一且规范的方法.因此,除非您缩小特定问题的范围,否则您可能就此任务的高级细节不会获得太多帮助.

The question about "how to create an onscreen keyboard" is very broad as there are many valid approaches to this, not one single and canonical way to do it. Therefore, you probably won't get much help about the high-level details of this task unless you can narrow down specific issues.

但是,就键盘事件而言,您可以使用

However, as far as keyboard events are concerned, you would use the Quartz Event Services API to fabricate keyboard events. Specifically, you are looking for CGEventCreateKeyboardEvent and CGEventPost.

// CGEvent functions
#import <ApplicationServices/ApplicationServices.h>

// kVK_* values
#import <Carbon/Carbon.h>

// press and release "abcd"
int virtualKeys[] = { kVK_ANSI_A, kVK_ANSI_B, kVK_ANSI_C, kVK_ANSI_D };

for (int i = 0; i < 4; i++)
{
    // press the letter
    CGEventRef event = CGEventCreateKeyboardEvent(NULL, virtualKeys[i], YES);
    CGEventPost(kCGHIDEventTap, event);
    CFRelease(event);

    // wait .1 seconds
    usleep(100000);

    // release the letter
    event = CGEventCreateKeyboardEvent(NULL, virtualKeys[i], NO);
    CGEventPost(kCGHIDEventTap, event);
    CFRelease(event);
}

对于大写字母,您需要在字母前按" kVK_Shift(并且也需要释放它).

For capitals, you need to "press" kVK_Shift before the letter (and you need to release it as well).

这篇关于如何使用Objective C按下键盘键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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