尝试使用JAVA读取滚动锁定状态 [英] Trying to read Scroll Lock status using JAVA
问题描述
我有以下几行代码,试图读取滚动锁的状态.
I have the below lines of code using which i am trying to read status of scroll lock.
我的程序启动时获得滚动锁定的状态. 但是我愿意实时获取状态. 请在下面进行指导
I get the status of scroll lock when my program starts. However i am willing to get the status realtime. Please guide on the below
package assignment;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import org.omg.PortableServer.THREAD_POLICY_ID;
public class ScrollLockOnOff {
public static void main(String[] args) throws InterruptedException
{
while(true)
{
Thread.sleep(1000);
Toolkit toolkit=Toolkit.getDefaultToolkit();
System.out.println(toolkit.getLockingKeyState(KeyEvent.VK_SCROLL_LOCK));
}
}
}
推荐答案
这是一个有趣的行为,它可以正确地报告初始状态,但要依赖后续事件处理(具有集中的顶层窗口或任务栏图标)来进行更新.
It’s an interesting behavior, to correctly report the initial state but to depend on subsequent event processing (having a focused top level window or tray icon) for updates.
如果我们有办法将AWT重置为其初始状态,它应该可以解决此问题.如果我们找不到这种可能性,那么直接的解决方法是运行一个新的JVM.由于具有相同属性的新JVM将使用高速缓存甚至共享内存中的资源,因此开销听起来要小得多.每秒执行一次操作没问题:
If we had a way to reset the AWT to its initial state, it should solve the issue. If we don’t find such a possibility, the straight-forward fix is to run a new JVM. Since a new JVM with the same properties will use resources in cache or even shared memory, the overhead is much smaller as it may sound. Performing the action once a second is no problem:
public class ScrollLockOnOff {
public static void main(String[] args)
throws InterruptedException, AWTException, IOException {
if(args.length == 1 && args[0].equals("VK_SCROLL_LOCK")) {
System.exit(Toolkit.getDefaultToolkit()
.getLockingKeyState(KeyEvent.VK_SCROLL_LOCK)? KeyEvent.VK_SCROLL_LOCK: 0);
return;
}
ProcessBuilder b = new ProcessBuilder(
Paths.get(System.getProperty("java.home"), "bin", "java").toString(),
"-classpath", System.getProperty("java.class.path"),
ScrollLockOnOff.class.getName(), "VK_SCROLL_LOCK"
).inheritIO();
while(true) {
Thread.sleep(1000);
int state = b.start().waitFor();
if(state != 0 && state != KeyEvent.VK_SCROLL_LOCK) {
System.err.println("failed");
break;
}
System.out.println(state == KeyEvent.VK_SCROLL_LOCK);
}
}
}
这篇关于尝试使用JAVA读取滚动锁定状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!