我正在开发 Java 程序。它必须以管理员身份运行应用程序,并在执行结束时执行其他操作。一开始,我用
String cmd[] = new String [3];
cmd [0] = "cmd";
cmd [1] = "/C";
cmd [2] = "runas /user:..."
Process p = Runtime.getRuntime().exec(cmd);
但问题是我无法输入密码(我试过了,但没有找到解决方案)。之后,我用 JNA 做了它,像这样:
boolean CreateProcessWithLogonW
(WString lpUsername,
WString lpDomain,
WString lpPassword,
int dwLogonFlags,
WString lpApplicationName,
WString lpCommandLine,
int dwCreationFlags,
Pointer lpEnvironment,
WString lpCurrentDirectory,
STARTUPINFO lpStartupInfo,
PROCESS_INFORMATION lpProcessInfo);
这里,问题是如何等待程序的执行直到这个过程结束(也许,在 JNA 中,有表格可以做到这一点,但是太大了,我不知道该怎么做...... )
我想到了另一种方法,但我不知道是否可行...像这样:
Kernel32 kernel32 = (Kernel32) Native.loadLibrary(Kernel32.class, W32APIOptions.UNICODE_OPTIONS);
Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference();
WinNT.HANDLE snapshot = kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0));
try
{
while (kernel32.Process32Next(snapshot, processEntry))
{
System.out.println(processEntry.th32ProcessID + "\t" + Native.toString(processEntry.szExeFile));
}
}
至此,我有了进程的 ID 和名称。有可能找到运行此进程的用户名吗??如果我成功了,我就可以做到(唯一以管理员身份运行的进程就是这个)
问候。
最佳答案
我解决了。
public boolean jambo_loco (int pid)
{
Kernel32 kernel32 = (Kernel32) Native.loadLibrary(Kernel32.class, W32APIOptions.UNICODE_OPTIONS);
Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference();
WinNT.HANDLE snapshot = kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0));
try
{
int i = 0;
int size = processEntry.dwSize.intValue();
while (kernel32.Process32Next(snapshot, processEntry) && i < size)
{
if (processEntry.th32ProcessID.intValue() == pid)
return true;
i++;
}
}
finally
{
kernel32.CloseHandle(snapshot);
}
return false;
}
一个循环
,在另一边,当它返回true
时多次调用这个方法。
问候。
关于java - 如何使用JNA 查找某个进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38223089/