超时后从 Java 锁定 Windows 桌面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7642900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 18:11:43  来源:igfitidea点击:

Lock windows desktop from Java after timeout

javawindowstimeoutlockout

提问by Daisetsu

I want my java app to lock the windows desktop after a specific timeout. I have a timer which works fine, but I can't seem to execute the command to lock the workstation.

我希望我的 Java 应用程序在特定超时后锁定 Windows 桌面。我有一个可以正常工作的计时器,但我似乎无法执行锁定工作站的命令。

javax.swing.Timer tim = new javax.swing.Timer(1000, new ActionListener() {
   public void actionPerformed(ActionEvent e) {
   System.out.println("CARD NOT PRESENT!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
   // LOCK SCREEN
   Runtime rt = Runtime.getRuntime();
   Process pr = rt.exec("%windir%/System32/rundll32.exe user32.dll,LockWorkStation");
   }
});

Is there some mistake in this? Or maybe an easier way to do this?

这有什么错误吗?或者也许有更简单的方法来做到这一点?

回答by Roman Malieiev

Try absolute location:

尝试绝对位置:

Runtime.getRuntime().exec("C:\Windows\System32\rundll32.exe user32.dll,LockWorkStation");

回答by Steve S.

This is working as well (tested on Windows 7 x86):

这也有效(在 Windows 7 x86 上测试):

final String path = System.getenv("windir") + File.separator + "System32" + File.separator + "rundll32.exe";
Process pr = rt.exec(path + " user32.dll,LockWorkStation");

回答by jayunit100

I think there is a better way to test this :

我认为有一个更好的方法来测试这个:

1) put the command in a .bat file.

1) 将命令放在 .bat 文件中。

2) Run the bat file. does it work ?

2)运行bat文件。它有效吗?

3) If so , call the .bat file in your code.

3) 如果是这样,请在您的代码中调用 .bat 文件。

4) Does it work ? If so, then you are done. I dont think there is any value in encoding windows specific code into runtime exec, just keep the bat file as a seperate file in your app .

4)它有效吗?如果是这样,那么你就完成了。我认为将特定于 Windows 的代码编码为运行时 exec 没有任何价值,只需将 bat 文件作为应用程序中的单独文件即可。

Runtime.exec sometimes fails because the paths arent the same inside the JVM as they are in the native os.

Runtime.exec 有时会失败,因为 JVM 中的路径与它们在本机操作系统中的路径不同。