gpt4 book ai didi

java - 如何移动(或使用)鼠标

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:12:15 35 4
gpt4 key购买 nike

如何使用 Java 和 JNA(Java native 访问)与 Windows API 交互?。我试图通过在鼠标输入流上排队鼠标事件来让鼠标做某事,并且代码有效,因为 SendInput(...) 方法返回 1 表明它已成功将事件排队,但鼠标本身什么也不做。

我的 SSCCE :

编辑:编辑以填充 dwFlags 字段。我已经尝试了几种常量组合,无论是单独组合还是位组合,但仍然没有成功。同样,SendInput 方法返回 1,因为它应该建议一个有效的方法,但鼠标没有移动:

import com.sun.jna.Native;
import com.sun.jna.platform.win32.WinDef.*;
import com.sun.jna.platform.win32.WinUser.*;
import com.sun.jna.win32.StdCallLibrary;

public class MouseUtils {
public interface User32 extends StdCallLibrary {
public static final long MOUSEEVENTF_MOVE = 0x0001L;
public static final long MOUSEEVENTF_VIRTUALDESK = 0x4000L;
public static final long MOUSEEVENTF_ABSOLUTE = 0x8000L;

User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class);
DWORD SendInput(DWORD dWord, INPUT[] input, int cbSize);
}

public static void main(String[] args) {
INPUT input = new INPUT();
input.type = new DWORD(INPUT.INPUT_MOUSE);

input.input.mi.dx = new LONG(500);
input.input.mi.dy = new LONG(500);
input.input.mi.mouseData = new DWORD(0);
input.input.mi.dwFlags = new DWORD(User32.MOUSEEVENTF_MOVE
| User32.MOUSEEVENTF_VIRTUALDESK | User32.MOUSEEVENTF_ABSOLUTE);
// input.input.mi.dwFlags = new DWORD(0x8000L);
input.input.mi.time = new DWORD(0);

INPUT[] inArray = {input};

int cbSize = input.size(); // mouse input struct size
DWORD nInputs = new DWORD(1); // number of inputs
DWORD result = User32.INSTANCE.SendInput(nInputs , inArray, cbSize);
System.out.println("result: " + result); // return 1 if the 1 event successfully inserted
}
}

编辑 2:

阅读更多内容后,我似乎对 JNA 数组的理解不足,我不得不从 C 数组的角度来思考,其中数组只是指向连续内存区域的指针。更多精彩即将到来(我希望!)。

最佳答案

JNA 文档 Using Structures And Unions阅读:

Unions are generally interchangeable with Structures, but require that you indicate which union field is active with the setType method before it can be properly passed to a function call.

我猜你错过了 setType 部分。此外,当使用 MOUSEEVENTF_ABSOLUTE 时,dxdy 被指定为鼠标坐标,而不是像素。

以下作品:

public interface User32 extends StdCallLibrary {
...
public static final int SM_CXSCREEN = 0x0;
public static final int SM_CYSCREEN = 0x1;
int GetSystemMetrics(int index);
}

public static void main(String[] args) {
...
input.input.setType("mi");
input.input.mi.dx = new LONG(500 * 65536 / User32.INSTANCE.GetSystemMetrics(User32.SM_CXSCREEN));
input.input.mi.dy = new LONG(500 * 65536 / User32.INSTANCE.GetSystemMetrics(User32.SM_CYSCREEN));
...
}

关于java - 如何移动(或使用)鼠标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8408435/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com