CGEventPostToPSN() not working for mouse clicking

自古美人都是妖i 提交于 2019-12-09 19:27:33

问题


I need to send mouse click events to an arbitrary process (not necessarily the front one) without bringing that process's window to the front.

This code works for sending a mouse click and letting the window server send it to whatever process it decides has focus:

#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;
}

I can send mouse click events via CGEventPost() just fine, but that requires the target process to have focus (which I am trying to avoid).

I can send keyboard events via CGEventPostToPSN() just fine, and as far as I can tell, mouse move events work too, what I'm having trouble with is mouse down/up events.

This code (pretty much the above, the only difference being that I specify myself which process to send the events to) does not work and I don't even know how to find out where it breaks down.

#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;
}

I've been stuck on this for a few days now, and I can't seem to figure it out. According to the documentation this is (as far as I can tell) exactly how it is supposed to be done.

I have tested this code on Snow Leopard and Lion, with the same results.

Could somebody who has had success with clicking via CGEventPostToPSN() please shed some insight on the proper way to accomplish this?

来源:https://stackoverflow.com/questions/9678239/cgeventposttopsn-not-working-for-mouse-clicking

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!