問(wèn)題描述
我正在編寫一個(gè)應(yīng)用程序,我需要在 Mac 上模擬按鍵事件,給定代表每個(gè)鍵的代碼.看來(lái)我需要使用 CGEventCreateKeyboardEvent
函數(shù)來(lái)創(chuàng)建事件.問(wèn)題是這個(gè)功能需要一個(gè)Mac鍵碼,而我有的是一個(gè)代表特定鍵的代碼.因此,例如,我收到:
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
- 這些都是在某處定義的數(shù)字常量.
KEY_CODE_SHIFT
or KEY_CODE_A
- these are both numeric constants defined somewhere.
我需要將這些常量轉(zhuǎn)換為 CGKeyCode
值.
I need to take these constants and turn them into CGKeyCode
values.
我目前的嘗試使用類似于this SO question的代碼.問(wèn)題是它只適用于可打印的字符.如果所有其他方法都失敗了,我不會(huì)對(duì)轉(zhuǎn)換進(jìn)行硬編碼,但這意味著我需要一個(gè)可能的 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 動(dòng)作的代碼:
Here's code to simulate a Cmd-S action:
CGKeyCode inputKeyCode = kVK_ANSI_S;
CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);
CGEventRef saveCommandDown = CGEventCreateKeyboardEvent(source, inputKeyCode, YES);
CGEventSetFlags(saveCommandDown, kCGEventFlagMaskCommand);
CGEventRef saveCommandUp = CGEventCreateKeyboardEvent(source, inputKeyCode, NO);
CGEventPost(kCGAnnotatedSessionEventTap, saveCommandDown);
CGEventPost(kCGAnnotatedSessionEventTap, saveCommandUp);
CFRelease(saveCommandUp);
CFRelease(saveCommandDown);
CFRelease(source);
CGKeyCode
只不過(guò)是一個(gè)無(wú)符號(hào)整數(shù):
A CGKeyCode
is nothing more than an unsigned integer:
typedef uint16_t CGKeyCode; //From CGRemoteOperation.h
您真正的問(wèn)題是將字符(可能是 NSString
)轉(zhuǎn)換為鍵碼.幸運(yùn)的是,Shortcut Recorder 項(xiàng)目的代碼可以在 SRKeyCodeTransformer.m
文件.它非常適合將字符串轉(zhuǎn)換為鍵碼并再次返回.
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.
這篇關(guān)于在 Mac OS X 中模擬按鍵事件的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!