检查是否按下了Shift键 [英] Check whether shift key is pressed

查看:137
本文介绍了检查是否按下了Shift键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个应用程序,应在启动时检查是否按下了Shift键.为此,我创建了一个负责该工作的小类:

I'm programming an application which should, when started, check whether the shift key is pressed. For that I have created a small class which is responsible for that:

import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;

public class KeyboardListener {

    private static boolean isShiftDown;

    static {
        KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(
            new KeyEventDispatcher() {
                public boolean dispatchKeyEvent(KeyEvent e) {
                    isShiftDown = e.isShiftDown();
                    return false;
                }
            });
    }

    public static boolean isShiftDown() {
        return isShiftDown;
    }

}

但是,如果在应用程序启动时已经按了Shift键,这似乎不起作用.以下检查始终执行else情况.

However, it seems that this is not working if the shift key was already pressed when the application started up. The following check always executes the else case.

if (KeyboardListener.isShiftDown()) {
    // ...
} else {
    // this always gets executed
}

是否有一种方法可以检查在应用程序启动时是否已经按下了Shift键?我知道可以使用WinAPI,但是我更喜欢Javaish的方式.

Is there a way of checking whether the shift key is pressed if it was already pressed when the application started? I know this is possible using WinAPI, but I would prefer a Javaish way of doing it.

提前谢谢!

推荐答案

我将其描述为一种hack,但是它确实解决了该问题(有一些缺点),因此我认为我将其作为一种可能性.

I'd characterize this as a hack, but it does solve the problem (with some downsides), so I figured I would mention it as a possibility.

您可以使用Robot类来模拟您的应用程序不关心的某些键(也许是功能键之一)的击键.注册KeyListener后立即运行此代码.您会看到一个按键事件,它将告诉您Shift是否关闭.

You can use the Robot class to simulate a keystroke of some key that your application doesn't care about (perhaps one of the function keys). Run this code right after you register your KeyListener. You'll see a key event which will tell you whether Shift is down.

警告:这将在系统中显示,就像用户实际按下并释放了F24(或您选择的任何键)一样.这可能会带来意想不到的副作用.

Warning: This will appear to the system as if the F24 (or whatever key you choose) had actually been pressed and released by the user. That could potentially have unexpected side-effects.

    (new Thread( )
    {
        @Override
        public void run( )
        {
            try
            {
                java.awt.Robot robot = new Robot();
                robot.delay( 100 );
                robot.keyPress( KeyEvent.VK_F24 );
                robot.keyRelease( KeyEvent.VK_F24 );
            }
            catch ( Exception e )
            {
            }
        }
    }).start( );

这篇关于检查是否按下了Shift键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆