我的软件出现了一个严重的问题。我正在制作一个与另一个现有软件(游戏)交互的程序。用户报告说他以管理员权限运行游戏,在这种情况下,我的程序停止为他工作。
简短的调查显示,有些人确实需要在管理员帐户下运行游戏,而有些人则不需要。如果我的程序能够检测到这一点并警告用户游戏是否在管理员帐户下运行,那就太好了:
如果用户单击“提升”,我会要求 Windows 提升运行我的 jar
文件的 java.exe
并调用典型的 UAC 对话框。
显然,这次的问题不是关于 java updater 而是关于 JRE
我的问题是:这可能吗? Windows 可以提升我的 java.exe
实例的权限吗? java有办法实现吗?或者我可以使用命令行命令吗?
我想避免重新启动程序(尽管这可能不是什么大问题)。
编辑:
如果您查看评论,您会发现应用程序的重新启动是不可避免的 - 进程只能启动提升,而不能变得提升。不幸的是,这有点转移了问题。基本上,它现在听起来更像是:“如何使用管理员权限重新启动我的应用程序?”。当然,除非有像两个 java.exe
共享一个 jar 之类的技巧...
最佳答案
如果仍然感兴趣:在 Windows 7 中我的 JavaElevator 可以工作。当在 Java 应用程序的 main 方法中使用时,它会提升正在运行的 Java 进程。只需添加 -elevate
作为最后一个程序参数,并在 main 方法中使用电梯。
电梯等级:
package test;
import com.sun.jna.Native;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.Kernel32Util;
import com.sun.jna.platform.win32.ShellAPI;
import com.sun.jna.platform.win32.WinDef;
/**
* Elevates a Java process to administrator rights if requested.
*/
public class JavaElevator {
/** The program argument indicating the need of being elevated */
private static final String ELEVATE_ARG = "-elevate";
/**
* If requested, elevates the Java process started with the given arguments to administrator level.
*
* @param args The Java program arguments
* @return The cleaned program arguments
*/
public static String[] elevate(String[] args) {
String[] result = args;
// Check for elevation marker.
boolean elevate = false;
if (args.length > 0) {
elevate = args[args.length - 1].equals(ELEVATE_ARG);
}
if (elevate) {
// Get the command and remove the elevation marker.
String command = System.getProperty("sun.java.command");
command = command.replace(ELEVATE_ARG, "");
// Get class path and default java home.
String classPath = System.getProperty("java.class.path");
String javaHome = System.getProperty("java.home");
String vm = javaHome + "\\bin\\java.exe";
// Check for alternate VM for elevation. Full path to the VM may be passed with: -Delevation.vm=...
if (System.getProperties().contains("elevation.vm")) {
vm = System.getProperty("elevation.vm");
}
String parameters = "-cp " + classPath;
parameters += " " + command;
Shell32.INSTANCE.ShellExecute(null, "runas", vm, parameters, null, 0);
int lastError = Kernel32.INSTANCE.GetLastError();
if (lastError != 0) {
String errorMessage = Kernel32Util.formatMessageFromLastErrorCode(lastError);
errorMessage += "\n vm: " + vm;
errorMessage += "\n parameters: " + parameters;
throw new IllegalStateException("Error performing elevation: " + lastError + ": " + errorMessage);
}
System.exit(0);
}
return result;
}
}
在Java应用程序的main方法中的用法:
public static void main(String[] args) {
String[] args1 = JavaElevator.elevate(args);
if (args1.length > 0) {
// Continue as intended.
...
我知道,这是一个非常基本的实现 - 足以解决我的日常问题之一:从 Eclipse 启动提升的进程。但也许它为某人指出了某个方向......
关于java - 在运行时提升 Java 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43883549/