要从Delphi中的服务名称/句柄中找到进程ID,可以使用Windows API函数OpenProcess
和GetModuleFileNameEx
。以下是一个简单的示例代码:
program GetProcessIDFromServiceName;
{$APPTYPE CONSOLE}
uses
Windows,
SysUtils;
function GetProcessIDFromServiceName(const ServiceName: string): DWORD;
var
hSCManager: SC_HANDLE;
hService: SC_HANDLE;
dwProcessID: DWORD;
dwBytesNeeded: DWORD;
dwError: DWORD;
begin
Result := 0;
hSCManager := OpenSCManager(nil, nil, SC_MANAGER_CONNECT);
if hSCManager = 0 then
Exit;
hService := OpenService(hSCManager, PChar(ServiceName), SERVICE_QUERY_STATUS);
if hService = 0 then
begin
CloseServiceHandle(hSCManager);
Exit;
end;
if QueryServiceStatus(hService, nil^, 0, dwBytesNeeded) then
begin
dwError := ERROR_INSUFFICIENT_BUFFER;
end
else
begin
dwError := GetLastError();
if dwError <> ERROR_INSUFFICIENT_BUFFER then
begin
CloseServiceHandle(hService);
CloseServiceHandle(hSCManager);
Exit;
end;
end;
dwBytesNeeded := dwBytesNeeded + 1024;
GetMem(lpServiceStatus, dwBytesNeeded);
try
if QueryServiceStatus(hService, lpServiceStatus^, dwBytesNeeded, dwBytesNeeded) then
begin
dwProcessID := lpServiceStatus.dwProcessId;
Result := dwProcessID;
end;
finally
FreeMem(lpServiceStatus);
end;
CloseServiceHandle(hService);
CloseServiceHandle(hSCManager);
end;
var
dwProcessID: DWORD;
begin
try
dwProcessID := GetProcessIDFromServiceName('YourServiceName');
if dwProcessID <> 0 then
WriteLn(Format('Process ID: %d', [dwProcessID]))
else
WriteLn('Service not found');
except
on E: Exception do
WriteLn(E.Message);
end;
ReadLn;
end.
请注意,此代码示例需要以管理员权限运行,以便能够访问服务信息。将“YourServiceName”替换为您要查询的服务名称。
这个示例代码使用了Windows API函数OpenSCManager
和OpenService
来打开服务控制管理器和服务。然后,它使用QueryServiceStatus
函数来获取服务的状态信息,包括进程ID。最后,它使用CloseServiceHandle
函数关闭服务和服务控制管理器的句柄。
领取专属 10元无门槛券
手把手带您无忧上云