使用Python获取Java的全局击键

时间:2019-02-17 20:40:40

标签: java python pipe

我正在为游戏HUD GUI编写程序,但是当窗口不在焦点上时java无法获得全局按键,因此,我不想用jnativeinterface做任何黑魔法,因为我需要它在两个Linux上都可以工作和窗户。我想解决这个问题的想法是将输出从python传递到Java,但我不确定如何做到这一点。

到目前为止,这是我的代码供参考:

我只是出于好奇而试图将java键侦听器分配给不存在的窗口。

package main;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.PointerInfo;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MainThread extends JFrame implements KeyListener{
    private static final long serialVersionUID = 1L;
    public static void main(String[] args) throws Exception {
        System.out.println("Jeffrey was here");
        JFrame win = new JFrame();
        JPanel wind = new JPanel();
        win.add(wind);
        win.setDefaultCloseOperation(EXIT_ON_CLOSE);
        win.setVisible(true);
        win.setLocation(500, 500);
        win.setResizable(false);
        win.setSize(300,50);
        win.setAlwaysOnTop(true);
        win.setTitle("Mouse Cordinates");
        JLabel xCord = new JLabel("");
        JLabel yCord = new JLabel("");
        wind.add(xCord);
        wind.add(yCord);
        while(true) {
            Thread.sleep(30);
            PointerInfo mouse = MouseInfo.getPointerInfo();
            Point poin = mouse.getLocation();
            xCord.setText("X cordinates: " + (int) poin.getX());
            yCord.setText("Y cordinates: " + (int) poin.getY());
        }
    }
    @Override
    public void keyPressed(KeyEvent arg0) {
        // TODO Auto-generated method stub
        int key = arg0.getKeyCode();
        if(key == KeyEvent.VK_W) {
            System.out.print("w pressed");
        }
    }
    @Override
    public void keyReleased(KeyEvent arg0) {
        // TODO Auto-generated method stub

    }
    @Override
    public void keyTyped(KeyEvent arg0) {
        // TODO Auto-generated method stub

    }
}

我需要它来检测何时没有焦点对准窗口时按下了键。

1 个答案:

答案 0 :(得分:0)

已经存在可以为您提供此选项的库(我知道这并不是您要找的东西(python和其他东西),但这可能是解决您问题的方法)。看看kristian's system hook代码段:

public static void main(String[] args) {
    // might throw a UnsatisfiedLinkError if the native library fails to load or a
    // RuntimeException if hooking fails
    GlobalKeyboardHook keyboardHook = new GlobalKeyboardHook(true); 
    keyboardHook.addKeyListener(new GlobalKeyAdapter() {
        @Override
        public void keyPressed(GlobalKeyEvent event) {
            System.out.println(event);
            if (event.getVirtualKeyCode() == GlobalKeyEvent.VK_ESCAPE)
                run = false;
        }

        @Override
        public void keyReleased(GlobalKeyEvent event) {
            System.out.println(event);
        }
    });

当然还有JNativeHook选项。


要查看其他一些已经存在的问题:

How to capture global key presses in java

How can I write a key listener to track all keystrokes in Java?