我需要将鼠标单击事件发送到任意进程(不一定是前面的进程),而不将该进程的窗口带到前面。
此代码用于发送鼠标单击并让窗口服务器将其发送到它认为具有焦点的任何进程:
#include <ApplicationServices/ApplicationServices.h>
int
main()
{
CGEventRef down, up;
down = CGEventCreateMouseEvent(
NULL,
kCGEventLeftMouseDown,
CGPointMake(16, 36),
kCGMouseButtonLeft
);
up = CGEventCreateMouseEvent(
NULL,
kCGEventLeftMouseUp,
CGPointMake(16, 36),
kCGMouseButtonLeft
);
CGEventPost(kCGHIDEventTap, down);
CGEventPost(kCGHIDEventTap, up);
CFRelease(down);
CFRelease(up);
return 0;
}
我可以通过 CGEventPost() 发送鼠标单击事件,但这需要目标进程具有焦点(我试图避免)。
我可以通过 CGEventPostToPSN() 发送键盘事件,据我所知,鼠标移动事件也可以工作,我遇到的问题是鼠标向下/向上事件。
这段代码(与上面差不多,唯一的区别是我自己指定将事件发送到哪个进程)不起作用,我什至不知道如何找出它崩溃的位置。
#include <ApplicationServices/ApplicationServices.h>
#include <Carbon/Carbon.h> /* for ProcessSerialNumber stuff */
#include <stdio.h>
int
main()
{
ProcessSerialNumber psn;
CGEventRef down, up;
if (GetFrontProcess(&psn) != noErr) {
printf("Unable to get front process\n");
return 1;
}
down = CGEventCreateMouseEvent(
NULL,
kCGEventLeftMouseDown,
CGPointMake(16, 36),
kCGMouseButtonLeft
);
up = CGEventCreateMouseEvent(
NULL,
kCGEventLeftMouseUp,
CGPointMake(16, 36),
kCGMouseButtonLeft
);
CGEventPostToPSN(&psn, down);
CGEventPostToPSN(&psn, up);
CFRelease(down);
CFRelease(up);
return 0;
}
我已经被这个问题困扰了好几天了,我似乎无法弄清楚。根据文档 https://developer.apple.com/library/mac/#documentation/Carbon/Reference/QuartzEventServicesRef/Reference/reference.html(据我所知)这正是应该如何完成的。
我在 Snow Leopard 和 Lion 上测试了这段代码,得到了相同的结果。
通过 CGEventPostToPSN() 成功点击的人能否就完成此操作的正确方法提供一些见解?