Windows上的Java中的全局热键问题

时间:2019-06-02 18:29:53

标签: java jna

我的Java应用程序需要全局热键支持。

我想出了一些代码(大部分是复制过来的),但是它不起作用。

HotkeyManager.java:

import java.awt.event.KeyEvent;

public class HotkeyManager extends Thread {
    public static void register() {
        User32.RegisterHotKey(null, 1, 0x000, KeyEvent.VK_F);
        new HotkeyManager().start();
    }

    public HotkeyManager() {

    }

    @Override
    public void run() {
        MSG msg = new MSG();
        while (true) {
              while (User32.PeekMessage(msg, null, 0, 0, User32.PM_REMOVE)) {
                   if (msg.message == User32.WM_HOTKEY) {
                       System.out.println("Hotkey pressed with id: " + msg.wParam);
                   }
              }

              try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

User32.java:

import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
import com.sun.jna.Pointer;
import com.sun.jna.win32.W32APIOptions;

public class User32 {
    static {
        Native.register(NativeLibrary.getInstance("user32", W32APIOptions.DEFAULT_OPTIONS));
    }

    public static final int MOD_ALT = 0x0001;
    public static final int MOD_CONTROL = 0x0002;
    public static final int MOD_SHIFT = 0x0004;
    public static final int MOD_WIN = 0x0008;
    public static final int WM_HOTKEY = 0x0312;
    public static final int PM_REMOVE = 0x0001;

    public static native boolean RegisterHotKey(Pointer hWnd, int id, int fsModifiers, int vk);
    public static native boolean UnregisterHotKey(Pointer hWnd, int id);
    public static native boolean PeekMessage(MSG lpMsg, Pointer hWnd, int wMsgFilterMin, int wMsgFilterMax, int wRemoveMsg);

}

MSG.java:

import java.util.Arrays;
import java.util.List;

import com.sun.jna.Pointer;
import com.sun.jna.Structure;

public class MSG extends Structure {
    public Pointer hWnd;
    public int lParam;
    public int message;
    public int time;
    public int wParam;
    public int x;
    public int y;

    @Override
    protected List getFieldOrder() {
        return Arrays.asList(new String[]{"hWnd", "lParam", "message", "time", "wParam", "x", "y"});
    }
}

它确实注册了热键(在程序运行时在系统中按“ F”不会有任何结果),但是我从没有任何输出到控制台。怎么了? 我也知道jintellitype和jnativehook。我不能先使用它,其次才能使用-它总是侦听所有硬件事件,包括鼠标移动和所有按键操作,我只会将其用作最后的选择。

1 个答案:

答案 0 :(得分:0)

我知道了。我必须在侦听消息的同一线程中注册热键。 User32.RegisterHotKey(null,1,0x000,KeyEvent.VK_F);进入run(),一切正常。