在 Mac OS X 中模拟按键事件
我正在编写一个应用程序,需要在 Mac 上模拟按键事件,并给出代表每个键的代码。看来我需要使用 CGEventCreateKeyboardEvent 函数来创建事件。问题是这个函数需要一个Mac键码,而我拥有的是代表特定键的代码。因此,例如,我收到:
KEY_CODE_SHIFT
或 KEY_CODE_A
- 这些都是在某处定义的数字常量。
我需要获取这些常量并将它们转换为 CGKeyCode 值。
我当前的尝试使用类似于这个SO问题的代码。问题是它只适用于可打印字符。如果一切都失败了,我不会对转换进行硬编码,但这意味着我需要一个可能的 CGKeyCode 值表,但我尚未找到该表。
有什么想法吗?
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
or KEY_CODE_A
- these are both numeric constants defined somewhere.
I need to take these constants and turn them into CGKeyCode
values.
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.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以下是模拟 Cmd-S 操作的代码:
CGKeyCode
只不过是一个无符号整数:您真正的问题将是转动一个字符(可能是一个
NSString
) 到一个键码中。幸运的是, Shortcut Recorder 项目的代码可以在SRKeyCodeTransformer.m
文件。它非常适合将字符串转换为键码并再次转换回来。Here's code to simulate a Cmd-S action:
A
CGKeyCode
is nothing more than an unsigned integer: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 theSRKeyCodeTransformer.m
file. It's great for transforming a string to a keycode and back again.以防万一有人需要 Swift 版本:
XCode 7.3 和 Swift 2.2:
上面的代码模拟 CMD-V 按下然后释放(又名:粘贴)。
Just in case some one needs a Swift version:
XCode 7.3 and Swift 2.2:
Code above simulates CMD-V pressed then released(AKA: paste).