CGEventPost-按住一个键(Shift) [英] CGEventPost - hold a key (shift)

查看:95
本文介绍了CGEventPost-按住一个键(Shift)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种设计带有修饰键的小面板的方法(例如,Shift,Command),并且必须像虚拟键盘一样单击它.

I'm looking for a way to design a little panel with modifier keys on it (shift, command for example) and have to possibility to click on it like a virtual keyboard.

我希望它具有这种行为:

I'd like it to have this behavior :

  • 单击虚拟键(Shift).
  • 按住Shift键并保持按下状态.
  • 用我的标准键盘输入一些内容.
  • 再次单击虚拟Shift键以将其释放.

这是我正在使用的代码:

here is the code I'm using :

CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateHIDSystemState);
CGEventRef shiftKeyDown = CGEventCreateKeyboardEvent(source, (CGKeyCode)56, YES);
CGEventRef shiftKeyUp = CGEventCreateKeyboardEvent(source, (CGKeyCode)56, NO);

CGEventPost(kCGAnnotatedSessionEventTap, shiftKeyDown);
CGEventPost(kCGAnnotatedSessionEventTap, shiftKeyUp);

CFRelease(shiftKeyUp);
CFRelease(shiftKeyDown);
CFRelease(source);

在再次单击它之前,我无法找到保持按下状态的方法.我虽然"Push On Push Off"按钮单元格类型是关键,但不幸的是没有. :-)

I can't find a way to keep it pressed until I click on it another time. I though "Push On Push Off" Button Cell type was the key but unfortunately no. :-)

有什么帮助吗?

提前谢谢.

推荐答案

实际上以这种方式按下的Shift键将在紧​​随不包含Shift标志的事件时自动释放.考虑到文档中的指示种类,这似乎是一个限制,或者可能是一个错误,表明以下情况:

A shift key virtually pressed that way, will get released automatically when followed by an event which doesn't contain a shift flag. This seems to be a limitation, or possibly a bug, considering the documentation sort of indicates otherwise: https://developer.apple.com/reference/coregraphics/cgevent/1456564-init#discussion

我发现要实现所需目标的唯一方法是设置事件侦听器,并将Shift标志添加到每个应通过Shift键修改的事件中.

The only way I found to achieve what you are looking for, is to setup an event listener, and add the shift flag to every event which should be modified by the Shift key.

有关如何监听键盘事件的示例: https://stackoverflow.com/a/31898592/1445812 (斯威夫特)

Example on how to listen to keyboard events: https://stackoverflow.com/a/31898592/1445812 (Swift)

有关如何将Shift标志用于拦截的事件的示例:

Example on how to had the shift flag to intercepted events:

event?.flags.insert(.maskShift)

希望这会有所帮助.如果有人知道如何做而不必在每个事件中添加标志,请告知.

Hope this helps. If anyone knows how to do the same without having to add the flags to every event, please do tell.

这篇关于CGEventPost-按住一个键(Shift)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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