Skip to content

Commit

Permalink
添加获取进程模块句柄方法
Browse files Browse the repository at this point in the history
  • Loading branch information
qiuapeng committed Nov 24, 2023
1 parent 7501d27 commit 32c4a66
Showing 1 changed file with 38 additions and 4 deletions.
42 changes: 38 additions & 4 deletions src/main/java/com/dnf/helper/Process.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
package com.dnf.helper;

import com.sun.jna.Native;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.Tlhelp32;
import com.sun.jna.platform.win32.WinBase;
import com.sun.jna.platform.win32.WinNT;
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.*;

public class Process {

/**
* 获取指定进程名的进程id
*
* @param processName 进程名称
* @return int
*/
public static int getProcessId(String processName) {
Tlhelp32.PROCESSENTRY32.ByReference pe = new Tlhelp32.PROCESSENTRY32.ByReference();

Expand All @@ -32,4 +37,33 @@ public static int getProcessId(String processName) {

return 0;
}

/**
* 获取指定进程模块句柄
*
* @param processId 进程id
* @param moduleName 模块名称
* @return long
*/
public static long getProcessModuleHandle(int processId, String moduleName) {
long result = 0;

WinNT.HANDLE hModuleSnap = Kernel32.INSTANCE.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPMODULE, new WinBase.DWORD(processId));
Tlhelp32.MODULEENTRY32W me = new Tlhelp32.MODULEENTRY32W();

if (Kernel32.INSTANCE.Module32FirstW(hModuleSnap, me)) {
do {
String currentProcessModuleName = Native.toString(me.szModule).toLowerCase();

if (currentProcessModuleName.equals(moduleName.toLowerCase())) {
WinDef.HMODULE hModule = me.hModule;
result = Pointer.nativeValue(hModule.getPointer());
break;
}
} while (Kernel32.INSTANCE.Module32NextW(hModuleSnap, me));
}

Kernel32.INSTANCE.CloseHandle(hModuleSnap);
return result;
}
}

0 comments on commit 32c4a66

Please sign in to comment.