c++ windows服务中若进程没有运行,怎么通过进程名获取进程绝对路径
时间: 2024-01-09 07:04:38 浏览: 43
如果指定的进程没有运行,那么就无法通过 Windows API 函数 `OpenProcess()` 和 `QueryFullProcessImageName()` 获取其绝对路径了。不过,可以通过查询注册表中的信息来获取进程的安装路径,前提是该进程在安装时将其路径写入了注册表。
下面是一个示例代码,可以获取指定进程的安装路径:
```c++
#include <windows.h>
#include <iostream>
#include <string>
#include <sstream>
// 通过注册表获取进程安装路径
std::wstring GetProcessPathFromRegistry(const std::wstring& processName)
{
std::wstring path;
HKEY hKey;
std::wstring key = L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\" + processName;
LONG result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, key.c_str(), 0, KEY_READ, &hKey);
if (result == ERROR_SUCCESS)
{
WCHAR szPath[MAX_PATH] = { 0 };
DWORD dwSize = MAX_PATH;
result = RegQueryValueEx(hKey, NULL, NULL, NULL, (LPBYTE)szPath, &dwSize);
if (result == ERROR_SUCCESS)
{
path = szPath;
}
RegCloseKey(hKey);
}
return path;
}
int main()
{
std::wstring processName = L"notepad.exe";
std::wstring processPath = GetProcessPathFromRegistry(processName);
if (!processPath.empty())
{
std::wcout << processName << L" 的安装路径为:" << processPath << std::endl;
}
else
{
std::wcout << processName << L" 没有安装!" << std::endl;
}
return 0;
}
```
注意,需要在程序中添加 `#include <windows.h>` 头文件,并且编译时需要链接 `advapi32.lib` 库。