Java中如何在windows桌面上添加鼠标监听事件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java中如何在windows桌面上添加鼠标监听事件相关的知识,希望对你有一定的参考价值。

比如说要在桌面上添加监听,鼠标在桌面的任何位置点击,然后产生事件。

去下载 JInvoke , 这是一个例子:如果网上找不到 JInvoke.jar,我传了一个到网站了,http://bet.s215.eatj.com/Browser.jsp 打开后在上级目录[..]的myfiles目录里能找到.ji.zip即是

import static com.jinvoke.win32.WinConstants.*;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

import com.jinvoke.Callback;
import com.jinvoke.JInvoke;
import com.jinvoke.NativeImport;
import com.jinvoke.Util;
import com.jinvoke.win32.User32;
import com.jinvoke.win32.structs.Msg;

public class MouseHook extends JPanel
static
JInvoke.initialize();


@NativeImport(library = "user32")
public native static int SetWindowsHookEx (int idHook, Callback hookProc, int hModule, int dwThreadId);

@NativeImport(library = "user32")
public native static int UnhookWindowsHookEx (int idHook);

public static final int WH_MOUSE_LL = 14;
static JFrame frame;

static TextArea mouseEventArea = new TextArea();
static JButton setHookBtn;
static JButton removeHookBtn;

public MouseHook()
super(new BorderLayout());

mouseEventArea.setText("1) Click the \"Set Mouse Hook\" button.\n" +
"2) Start clicking anywhere on the desktop. Mouse clicks will be captured here.\n" +
"3) Stop the mouse hook by clicking the \"Remove Mouse Hook\" button.\n\n");

JScrollPane MouseEventPane = new JScrollPane(mouseEventArea);

add(MouseEventPane, BorderLayout.CENTER);

JPanel buttonPanel = new JPanel();
buttonPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));

setHookBtn = new JButton("Set Mouse Hook");
setHookBtn.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent arg0)
setMouseHook();
);

removeHookBtn = new JButton("Remove Mouse Hook");
removeHookBtn.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent arg0)
unsetMouseHook();
);
removeHookBtn.setEnabled(false);
buttonPanel.add(setHookBtn);
buttonPanel.add(removeHookBtn);
add(buttonPanel, BorderLayout.SOUTH);


private void setMouseHook()
setHookBtn.setEnabled(false);
removeHookBtn.setEnabled(true);

// This hook is called in the context of the thread that installed it.
// The call is made by sending a message to the thread that installed the hook.
// Therefore, the thread that installed the hook must have a message loop.
//
// We crate a new thread as we don't want the AWT Event thread to be stuck running a message pump
// nor do we want the main thread to be stuck in running a message pump
Thread hookThread = new Thread(new Runnable()

public void run()
if (MouseProc.hookHandle == 0)
int hInstance = User32.GetWindowLong(Util.getWindowHandle(frame), GWL_HINSTANCE);

MouseProc.hookHandle = SetWindowsHookEx(WH_MOUSE_LL,
new Callback(MouseProc.class, "lowLevelMouseProc"),
hInstance,
0);

// Standard message dispatch loop (message pump)
Msg msg = new Msg();
while (User32.GetMessage(msg, 0, 0, 0))
User32.TranslateMessage(msg);
User32.DispatchMessage(msg);


else
mouseEventArea.append("The Hook is already installed.\n");

);
hookThread.start();


private void unsetMouseHook()
setHookBtn.setEnabled(true);
removeHookBtn.setEnabled(false);
UnhookWindowsHookEx(MouseProc.hookHandle);
MouseProc.hookHandle = 0;


private static void createAndShowGUI()
//Create and set up the window.
frame = new JFrame("Mouse Hook");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

MouseHook MouseEventsWindow = new MouseHook();
MouseEventsWindow.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
//Add content to the window.
frame.add(MouseEventsWindow, BorderLayout.CENTER);

//Display the window.
frame.pack();

frame.setBounds(300, 200, 750, 600);
frame.setVisible(true);


public static void main(String[] args)
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable()
public void run()
createAndShowGUI();

);




class MouseProc
static int hookHandle;

@NativeImport(library = "user32")
public native static int CallNextHookEx (int idHook, int nCode, int wParam, int lParam);

static
JInvoke.initialize();


public static int lowLevelMouseProc(int nCode, int wParam, int lParam )
if (nCode < 0)
return CallNextHookEx(hookHandle, nCode, wParam, lParam);

if (nCode == HC_ACTION)
MouseHookStruct mInfo = Util.ptrToStruct(lParam, MouseHookStruct.class);
String message = "Mouse pt: (" + mInfo.pt.x + ", " + mInfo.pt.y + ") ";
switch (wParam)

case WM_LBUTTONDOWN:
message += "Left button down";
break;
case WM_LBUTTONUP:
message += "Left button up";
break;
case WM_MOUSEMOVE:
message += "Mouse moved";
break;
case WM_MOUSEWHEEL:
message += "Mouse wheel rotated";
break;
case WM_RBUTTONDOWN:
message += "Right button down";
break;
case WM_RBUTTONUP:
message += "Right button down";
break;

System.out.println(message);
// MouseHook.mouseEventArea.append(message+"\n");


return CallNextHookEx(hookHandle, nCode, wParam, lParam);



=============================================
import com.jinvoke.NativeStruct;
import com.jinvoke.win32.structs.Point;

@NativeStruct
public class MouseHookStruct //MSLLHOOKSTRUCT
public Point pt = new Point();
public int mouseData;
public int flags;
public int time;
public int dwExtraInfo;
参考技术A 还是得调用windows API 看看JNI吧

如何在Java桌面应用程序中停止无限循环以移动鼠标

我正在尝试创建一个桌面程序来移动鼠标,直到我按下java中的字母“q”。我创建了一个窗口(JFrame),当我按下按钮时,鼠标开始移动。我的疑问与这部分有关:

while (true) {
        for (int j = 1500; j <1600; j++) {
            robot.mouseMove(j, 0);
            robot.delay(100);
        }
    }

如何通过按字母来阻止这个无限循环?

public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_Q) {
        System.exit(0);
    }
}

为什么这不起作用? (我需要按一个字母,因为鼠标在程序运行时无法使用)提前感谢。

答案

首先,您可能不得不放弃事件处理程序。如果在awt事件队列上运行while(true),那么你正在占用整个GUI,难怪它没有响应;从鼠标事件返回后才能触发其他事件。

你能提供更多代码吗?这还不足以解释这种行为。

您可能需要启动一个线程来执行此工作。

更新:

而不是同步调用JavaRobot();方法,您需要在一个线程中运行它。用于测试的丑陋黑客版本:

(new Thread(() -> JavaRobot())).start();

更干净的版本可能会将线程保存在变量中,因此您可以使用另一个按钮来中断它。如果您不想自己处理线程但仍然在线程中运行任务,那么您也可以使用执行程序服务apis。

以上是关于Java中如何在windows桌面上添加鼠标监听事件的主要内容,如果未能解决你的问题,请参考以下文章

win10系统怎么在桌面添加备注

Java JTable 添加了一个键盘事件,和鼠标点击事件的监听,如何在我键盘事件起作用时,让鼠标事件失效

win10怎么在桌面添加快捷方式

如何在 Windows 窗体 C# 中伪造鼠标光标位置?

JS DOM基础 事件概述 事件流 事件处理方法 添加监听器 事件类型 事件对象 事件委托

如何开启Windows远程桌面服务