GetModuleFileName我想在這裏做的正是正在做什麼:How do I GetModuleFileName() if I only have a window handle (hWnd)?(轉換C#與Java JNA) - 從HWND
但在Java,而不是C#。
到目前爲止,我已經成功地這樣:
public static final int PROCESS_QUERY_INFORMATION = 0x0400;
public interface User32 extends StdCallLibrary {
User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class);
int GetWindowThreadProcessId(HWND hwnd, IntByReference pid);
};
public interface Kernel32 extends StdCallLibrary {
Kernel32 INSTANCE = (Kernel32)Native.loadLibrary("kernel32", Kernel32.class);
public Pointer OpenProcess(int dwDesiredAccess, boolean bInheritHandle, int dwProcessId);
public int GetTickCount();
};
public interface psapi extends StdCallLibrary {
psapi INSTANCE = (psapi)Native.loadLibrary("psapi", psapi.class);
int GetModuleFileNameExA (Pointer process, Pointer hModule, byte[] lpString, int nMaxCount);
};
public static String getModuleFilename(HWND hwnd)
{
byte[] exePathname = new byte[512];
Pointer zero = new Pointer(0);
IntByReference pid = new IntByReference();
User32.INSTANCE.GetWindowThreadProcessId(hwnd, pid);
System.out.println("PID is " + pid.getValue());
Pointer process = Kernel32.INSTANCE.OpenProcess(PROCESS_QUERY_INFORMATION, false, pid.getValue());
int result = psapi.INSTANCE.GetModuleFileNameExA(process, zero, exePathname, 512);
String text = Native.toString(exePathname).substring(0, result);
return text;
}
所給出的窗口句柄是有效的,而PID總是成功打印。 「Process
」似乎返回一個值,但「result
」始終爲零。任何人都知道JNA會告訴我我的錯誤在哪裏?
編輯:最後,成功!問題是這條線(其中第一個值必須是1040
):
Pointer process = Kernel32.INSTANCE.OpenProcess(1040, false, pid.getValue());
有趣。我假設你的意思是'0x1040'?根據MSDN,這是「PROCESS_QUERY_LIMITED_INFORMATION」和「PROCESS_DUP_HANDLE」的聯合。如果你只是使用'0x1000'(刪除'PROCESS_DUP_HANDLE')會發生什麼?我猜測它正在切換到「PROCESS_QUERY_LIMITED_INFORMATION」,這有所作爲。 –
P.S.這是基於http://msdn.microsoft.com/en-us/library/ms684880(v=VS.85).aspx。 –