在Mac OS X中模拟按键事件 [英] Simulating key press events in Mac OS X

查看:649
本文介绍了在Mac OS X中模拟按键事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个应用程序,我需要在Mac上模拟按键事件,给出代表每个键的代码。看来我需要使用 CGEventCreateKeyboardEvent 函数来创建事件。问题是,这个函数需要一个Mac键码,我所拥有的是一个代表特定键的代码。例如,我收到:

I'm writing an app where I need to simulate key press events on a Mac, given a code that represents each key. It seems I need to use the CGEventCreateKeyboardEvent function to create the event. The problem is that this function needs a Mac keycode, and what I have is a code that represents the specific key. So, for example, I receive:

KEY_CODE_SHIFT KEY_CODE_A

KEY_CODE_SHIFT or KEY_CODE_A - these are both numeric constants defined somewhere.

我需要将这些常量转换为 CGKeyCode 值。

I need to take these constants and turn them into CGKeyCode values.

我当前的尝试使用类似于这个SO问题。问题是它只适用于可打印字符。如果所有的失败,我不是在硬编码的转换,但这将意味着我需要一个可能的CGKeyCode值的表,我还没有找到。

My current attempt uses code similar to this SO question. The problem is that it only works for printable characters. If all else fails, I'm not above hard coding the conversion, but that would mean that I'd need a table of possible CGKeyCode values, which I have not yet been able to find.

任何想法?

推荐答案

> Cmd - S action:

Here's code to simulate a Cmd-S action:

CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);
CGEventRef saveCommandDown = CGEventCreateKeyboardEvent(source, (CGKeyCode)1, YES);
CGEventSetFlags(saveCommandDown, kCGEventFlagMaskCommand);
CGEventRef saveCommandUp = CGEventCreateKeyboardEvent(source, (CGKeyCode)1, NO);

CGEventPost(kCGAnnotatedSessionEventTap, saveCommandDown);
CGEventPost(kCGAnnotatedSessionEventTap, saveCommandUp);

CFRelease(saveCommandUp);
CFRelease(saveCommandDown);
CFRelease(source);

A CGKeyCode 整数:

typedef uint16_t CGKeyCode;  //From CGRemoteOperation.h

你真正的问题将是一个字符c> NSString )转换为键码。幸运的是,快捷记录器项目中的代码只需在 SRKeyCodeTransformer.m 文件。非常适合将字符串转换为键码,然后返回。

Your real issue will be turning a character (probably an NSString) into a keycode. Fortunately, the Shortcut Recorder project has code that will do just that in the SRKeyCodeTransformer.m file. It's great for transforming a string to a keycode and back again.

这篇关于在Mac OS X中模拟按键事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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