Date
May. 19th, 2024
 
2024年 4月 12日

Post: OS X: Simulating mouse input programmatically

OS X: Simulating mouse input programmatically

Published 12:08 Aug 16, 2016.

Created by @ezra. Categorized in #Programming, and tagged as #macOS.

Source format: Markdown

Table of Content

玩过远程辅助工具小伙伴应该都对模拟鼠标事件不陌生, 要做到这件事, 可以使用 Quartz Event Services

先来一个 Demo, 首先要引入 ApplicationServices:

#include <ApplicationServices/ApplicationServices.h>

接下来, 要模拟事件, 首先需要创建事件:

CGPoint p1 = CGPointMake(500, 500);
CGPoint p2 = CGPointMake(700, 700);

// Move to p1
CGEventRef move1 = CGEventCreateMouseEvent(
    NULL, kCGEventMouseMoved, p1,
    kCGMouseButtonLeft // ignored
);
// Move to p2
CGEventRef move2 = CGEventCreateMouseEvent(
    NULL, kCGEventMouseMoved, p2,
    kCGMouseButtonLeft // ignored
);
// Left button down at p2
CGEventRef click1_down = CGEventCreateMouseEvent(
    NULL, kCGEventLeftMouseDown, p2,
    kCGMouseButtonLeft
);
// Left button up at p2
CGEventRef click1_up = CGEventCreateMouseEvent(
    NULL, kCGEventLeftMouseUp, p2,
    kCGMouseButtonLeft
);

上面我们创建了两个坐标点, 并创建了移动鼠标和鼠标左键按下、放开的事件。

现在, 执行它们:

// Execute events
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);

我们分别执行了前面创建的四个事件, 为了让显示效果更明显, 我们在执行事件的代码之间加入了 sleep()

事件执行之后, 不要忘记进行释放。

Pinned Message
HOTODOGO
I'm looking for a SOFTWARE PROJECT DIRECTOR / SOFTWARE R&D DIRECTOR position in a fresh and dynamic company. I would like to gain the right experience and extend my skills while working in great teams and big projects.
Feel free to contact me.
For more information, please view online résumé or download PDF
本人正在寻求任职 软件项目经理 / 软件技术经理 岗位的机会, 希望加⼊某个新鲜⽽充满活⼒的公司。
如有意向请随时 与我联系
更多信息请 查阅在线简历下载 PDF