如何通过 Mac 终端模拟鼠标点击?

13

有没有不需要使用程序或脚本的方法来完成这个任务?(也许可以通过 osascript 实现?)

2个回答

38

您可以使用Applescript自动化鼠标单击。

tell application "System Events"
    tell application process "Application_Name"
        key code 53
        delay 1
        click (click at {1800, 1200})
    end tell
end tell
如果您想在浏览器窗口中进行点击操作,可以使用JavaScript帮助下的AppleScript。
tell application "safari"
    activate
    do JavaScript "document.getElementById('element').click();"
end tell

通过终端,您可以创建一个文本文件并命名为click.m或其他您喜欢的名称,使用以下代码保存:

// File:
// click.m
//
// Compile with:
// gcc -o click click.m -framework ApplicationServices -framework Foundation
//
// Usage:
// ./click -x pixels -y pixels
// At the given coordinates it will click and release.
//
// From http://hints.macworld.com/article.php?story=2008051406323031
#import <Foundation/Foundation.h>
#import <ApplicationServices/ApplicationServices.h>

int main(int argc, char *argv[]) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSUserDefaults *args = [NSUserDefaults standardUserDefaults];

    int x = [args integerForKey:@"x"];
    int y = [args integerForKey:@"y"];

    CGPoint pt;
    pt.x = x;
    pt.y = y;

    CGPostMouseEvent( pt, 1, 1, 1 );
    CGPostMouseEvent( pt, 1, 1, 0 );

    [pool release];
    return 0;
}
按照指示进行编译。
gcc -o click click.m -framework ApplicationServices -framework Foundation

并将其移动到适当的系统文件夹中,以便更加方便

sudo mv click /usr/bin
sudo chmod +x /usr/bin/click

现在您可以运行一个简单的终端命令来操作鼠标。

click -x [coord] -y [coord]

注意:Jardel Weyrich在这里提供了更详细的代码示例,而John Dorian在这里提供了一个很棒的Java解决方案。


0

嗨。 我也有同样的问题,但我不确定你是否在寻找这个,它可以让你将鼠标移动到屏幕上给定的坐标并执行点击。不过需要 intel 处理器,而我没有,所以我无法使用它,但我会提供任何你需要的帮助。链接:http://hints.macworld.com/article.php?story=2008051406323031


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接