从开放运行工具中停止Win + R.

gri*_*s21 5 java javafx keyevent

在我的javafx程序中有一个弹出窗口,它允许用户按键,然后相应地设置标签.我的问题是关键组合是底层操作系统的快捷方式,例如,如果用户按下Win + R然后Run.exe启动,但我的程序应该只将标签设置为"Win + R".我的问题是如何阻止关键事件触发操作系统快捷方式.

这是相关的代码.

public void showInput() {
        Set codes = new HashSet();

        Stage inputWindow = new Stage();
        GridPane pane = new GridPane();
        Scene scene = new Scene(pane);
        Label label = new Label("Here comes the pressed keys");

        scene.setOnKeyPressed(e -> {
            e.consume();
            int code = e.getCode().ordinal();

            if (label.getText().equals("Here comes the pressed keys")){
                codes.add(code);
                label.setText(String.valueOf(e.getCode().getName()));

            } else if (!codes.contains(code)){
                codes.add(code);
                label.setText(label.getText() + "+" + e.getCode().getName());
            }
        });

        scene.setOnKeyReleased(e -> {
            e.consume();
            inputWindow.close();
        });

        pane.add(label, 0, 0);

        inputWindow.setScene(scene);
        inputWindow.show();
    }
Run Code Online (Sandbox Code Playgroud)

我试过e.consume()但它没有帮助.

rus*_*tyx 3

使用JNA是可能的,但这是一个坏主意。不要拦截众所周知的组合键。

尽管如此,下面是一个工作示例。它基本上使用SetWindowsHookExWin32 API,然后在钩子回调中阻止Win+键组合。R

import com.sun.jna.platform.win32.*;

public class Test {

    public static User32.HHOOK hHook;
    public static User32.LowLevelKeyboardProc lpfn;

    public static void main(String[] args) throws Exception {
        WinDef.HMODULE hMod = Kernel32.INSTANCE.GetModuleHandle(null);
        lpfn = new User32.LowLevelKeyboardProc() {
            boolean winKey = false;
            public WinDef.LRESULT callback(int nCode, WinDef.WPARAM wParam, WinUser.KBDLLHOOKSTRUCT lParam) {
                if (lParam.vkCode == 0x5B)
                    winKey = (lParam.flags & 0x80) == 0;
                if (lParam.flags == 0 && lParam.vkCode == 0x52 && winKey) {
                    System.out.println("Win-R pressed");
                    return new WinDef.LRESULT(-1);
                }
                return User32.INSTANCE.CallNextHookEx(hHook, nCode, wParam, lParam.getPointer());
            }
        };
        hHook = User32.INSTANCE.SetWindowsHookEx(User32.WH_KEYBOARD_LL, lpfn, hMod, 0);
        if (hHook == null) {
            System.out.println("Unable to set hook");
            return;
        }
        User32.MSG msg = new User32.MSG();
        while (User32.INSTANCE.GetMessage(msg, null, 0, 0) != 0) {
        }
        if (User32.INSTANCE.UnhookWindowsHookEx(hHook))
            System.out.println("Unhooked");
    }
}
Run Code Online (Sandbox Code Playgroud)

(所需的 JNA JAR 依赖项是net.java.dev.jna : platform