问题
I trying to get process name from the process id, and I've use GetModuleFileNameEx and I write this function.
char* ProcessName(ULONG_PTR ProcessId)
{
char szBuffer[MAX_PATH+1];
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ | PROCESS_TERMINATE, FALSE, ProcessId);
if(GetModuleFileNameEx(hProcess, NULL, szBuffer, MAX_PATH) == 0)
sprintf(szBuffer, "null");
CloseHandle(hProcess);
return szBuffer;
}
the output is Full-Path&Process-Name, and I want split it so I can get the process-name without Full-Path.
Is there any way to do this, or any other function can I use it to get process name from its process id?
回答1:
First: you're returning a pointer to local memory and that is going to end in tears
char* ProcessName(ULONG_PTR ProcessId) {
char szBuffer[MAX_PATH+1];
...
return szBuffer;
}
Aside from that, you can use _splitpath_s() or the like to get the filename from your path, or the PathFindFileName function available on Windows platforms with the shell API
#include "windows.h"
#include "Psapi.h"
#include "Shlwapi.h"
#include <string>
#include <iostream>
#pragma comment(lib, "Shlwapi.lib")
std::string ProcessName(DWORD ProcessId)
{
std::string name;
HANDLE Handle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, ProcessId);
if (Handle) {
TCHAR Buffer[MAX_PATH];
if (GetModuleFileNameEx(Handle, 0, Buffer, MAX_PATH)) {
name = std::string(PathFindFileName(Buffer));
}
else {
// Now would be a good time to call GetLastError()
}
CloseHandle(Handle);
}
return name;
}
int main() {
std::cout << ProcessName(GetCurrentProcessId());
return 0;
}
You can test this code on a recent MSVC compiler here
回答2:
You can use PathFindFileName() to get a file name from path. https://msdn.microsoft.com/en-us/library/windows/desktop/bb773589%28v=vs.85%29.aspx
回答3:
this gets the file name only from the full path it searches the last characters for \ then moduleNameOnly is the last bit minus the \ i the "strrchr" is the char version of wcsrchr.
wchar_t* moduleNameOnly = wcsrchr(szModName, L'\\')+1;
来源:https://stackoverflow.com/questions/30254793/getmodulefilenameex-split-output