在OS X中以编程方式模拟鼠标输入 [英] Simulating mouse input programmatically in OS X

查看:99
本文介绍了在OS X中以编程方式模拟鼠标输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从OS X中的程序模拟鼠标的动作?具体来说,简短的版本是我正在尝试使用两个网络摄像头来模拟触摸屏.因此,假设我可以获得X,Y位置,是否可以通过鼠标移动或单击将信息发送到OS?

Is it possible to simulate the actions of a mouse from a program in OS X? Specifically, the short version is that I'm trying to simulate a touchscreen using two webcams. So assuming I can get X,Y positions, can I send information to the OS as a mouse movement or click?

编辑-或者,如果在其他操作系统中特别容易,我愿意考虑.

Edit- Or if it's particularly easy in another operating system I'd be willing to consider that.

推荐答案

是的,有可能.您可以使用 Quartz事件服务模拟输入事件.

Yes, it is possible. You can use the Quartz Event Services to simulate input events.

假设使用C,我编写了一个简单的示例:

Assuming C, I wrote this quick example:

#include <ApplicationServices/ApplicationServices.h>
#include <unistd.h>

int main() {
    // Move to 200x200
    CGEventRef move1 = CGEventCreateMouseEvent(
        NULL, kCGEventMouseMoved,
        CGPointMake(200, 200),
        kCGMouseButtonLeft // ignored
    );
    // Move to 250x250
    CGEventRef move2 = CGEventCreateMouseEvent(
        NULL, kCGEventMouseMoved,
        CGPointMake(250, 250),
        kCGMouseButtonLeft // ignored
    );
    // Left button down at 250x250
    CGEventRef click1_down = CGEventCreateMouseEvent(
        NULL, kCGEventLeftMouseDown,
        CGPointMake(250, 250),
        kCGMouseButtonLeft
    );
    // Left button up at 250x250
    CGEventRef click1_up = CGEventCreateMouseEvent(
        NULL, kCGEventLeftMouseUp,
        CGPointMake(250, 250),
        kCGMouseButtonLeft
    );

    // Now, execute these events with an interval to make them noticeable
    CGEventPost(kCGHIDEventTap, move1);
    sleep(1);
    CGEventPost(kCGHIDEventTap, move2);
    sleep(1);
    CGEventPost(kCGHIDEventTap, click1_down);
    CGEventPost(kCGHIDEventTap, click1_up);

    // Release the events
    CFRelease(click1_up);
    CFRelease(click1_down);
    CFRelease(move2);
    CFRelease(move1);

    return 0;
}

假设使用GCC,请使用以下命令进行编译:

And assuming GCC, compile with:

gcc -o program program.c -Wall -framework ApplicationServices

享受魔术.

这篇关于在OS X中以编程方式模拟鼠标输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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