//查找指定的进程,然后返回进程ID procedure FindAProcess(const AFilename:string; const PathMatch:Boolean; var ProcessID: DWORD); //AFilename为要查找(进程ID)的文件名(可以包行路径) //PathMatch为查找的时候是否匹配路径 var lppe:TProcessEntry32; SsHandle:Thandle; FoundAProc, FoundOK:boolean; begin SsHandle := CreateToolHelp32SnapShot(TH32CS_SNAPALL,0); FoundAProc := Process32First(Sshandle,lppe); //枚举Process,然后判断是否是所要查找的Process while FoundAProc do begin //根据PathMatch的值来决定匹配的方式 if PathMatch then FoundOK:=AnsiStricomp(lppe.szExefile,PChar(AFilename))=0 else FoundOK:=AnsiStricomp(PChar(ExtractFilename(lppe.szExefile)),PChar(ExtractFilename(AFilename)))=0;
if FoundOK then begin ProcessID:=lppe.th32ProcessID; break; end; FoundAProc :=Process32Next(SsHandle,lppe); end; // if not FoundAProc then showmessage(SysErrorMessage(GetLastError)); CloseHandle(SsHandle); end;
//激活或者停止指定的权限 function EnabledDebugPrivilege(const bEnabled: Boolean):Boolean; var hToken: THandle; tp: TOKEN_PRIVILEGES; a: DWORD; const SE_DEBUG_NAME = 'SeDebugPrivilege'; begin Result:=False; //打开当前Process的令牌(我一直叫Token为令牌) if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, hToken)) then begin //调整令牌的权限,也就是加上或者取消调试权限(SE_DEBUG_NAME) tp.PrivilegeCount :=1; LookupPrivilegeValue(nil,SE_DEBUG_NAME ,tp.Privileges[0].Luid); if bEnabled then tp.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED else tp.Privileges[0].Attributes := 0; a:=0; AdjustTokenPrivileges(hToken,False,tp,SizeOf(tp),nil,a); Result:= GetLastError = ERROR_SUCCESS; CloseHandle(hToken); end; end;
//在指定的进程中插入一个DLL文件 function AttachToProcess(const HostFile, GuestFile : string;const PID:DWORD=0):DWORD; //HostFile为要绑定的宿主文件(Exe文件),GuestFile为要嵌入的客户文件(Dll文件) //如AttachToProcess('D:\TESTDLL.DLL','Notepad.exe') ; var hRemoteProcess: THandle; dwRemoteProcessId:DWORD; cb:DWORD; pszLibFileRemote: Pointer; iReturnCode:Boolean; TempVar:DWORD; pfnStartAddr:TFNThreadStartRoutine; pszLibAFilename: PwideChar; begin Result:=0; //激活当前Process的SE_DEBUG_NAME权限,如果不激活的话,一些服务进程将无法 //打开 EnabledDebugPrivilege(True);