在 Mac OS X 上模拟鼠标点击对某些应用程序不起作用
我正在用 C++ 编写适用于 Mac OS X 10.6 及更高版本的应用程序.应用程序的一部分需要模拟鼠标移动和鼠标点击.我目前通过使用 CGEventPost(kCGHIDEventTap, event);
发布 CGEvent
对象来做到这一点.
I'm writing an application for Mac OS X 10.6 and later in C++. One part of the application needs to simulate mouse movement and mouse clicks. I do this currently by posting CGEvent
objects using CGEventPost(kCGHIDEventTap, event);
.
这在大多数情况下是有效的 - 我可以很好地模拟鼠标移动和点击,但在某些方面似乎失败了.例如:
This works, for the most part - I can simulate mouse movement and clicks just fine, but it seems to fail in some areas. For example:
- 在 Mozilla Firefox 和 Safari 中,我可以点击所有菜单,但无法点击网站内的链接.当我尝试时,链接被突出显示,但浏览器从不跟随链接.但是,我可以右键单击链接,选择在新选项卡中打开链接",一切都按预期工作.已解决 - 使用
CGEventCreateMouseEvent(...)
创建鼠标事件使事件在网络浏览器中工作. - 我可以单击仪表板"图标来打开仪表板,但我无法单击任何仪表板小部件上的i"按钮.同样,点击来自 Spotlight 搜索小部件的任何搜索结果也不起作用.
- In Mozilla Firefox and Safari, I can click on all the menus, but cannot click on a link within a website. When I try, the link is highlighted, but the browser never follows the link. However, I can right-click on a link, select "open link in new tab", and everything works as expected. Solved - creating the mouse event using
CGEventCreateMouseEvent(...)
makes the event work within web browser. - I can click on the "Dashboard" icon to brink up the dashboard, but I cannot click on the "i" button on any of the dashboard widgets. Similarly, clicking on any of the search results from the spotlight search widget doesn't work either.
这种不一致是沿着应用程序边界的.可能是什么原因?
This inconsistency is along application boundaries. What might be the cause?
推荐答案
你需要做的是让这些应用程序相信你实际上产生了点击是明确设置鼠标上点击状态"字段的值up 事件为 1(默认为 0).下面的代码将做到这一点:
What you need to do to convince these applications that you have in fact generated a click is to explicitly set the value of the "click state" field on the mouse up event to 1 (it defaults to 0). The following code will do it:
CGEventSetIntegerValueField(event, kCGMouseEventClickState, 1);
鼠标按下时也必须设置为 1,但使用 CGEventCreateMouseEvent() 而不是 CGEventCreate() 为您完成.
It also has to be set to 1 for the mouse down, but by using CGEventCreateMouseEvent() rather than CGEventCreate() that gets done for you.
我已经对此进行了测试,它在仪表板和 Spotlight 搜索结果中的i"按钮中有效.
I have tested this and it works in the 'i' buttons in the dashboard and the Spotlight search results.
(顺便说一句,如果您正在模拟双击,则需要将第二次单击的鼠标按下和鼠标抬起事件的单击状态设置为 2.)
(As an aside, if you were simulating a double click you would need to set the click state to 2 for both the mouse down and mouse up events of the second click.)
相关文章