GetModuleFileNameEx - Split output

泄露秘密 提交于 2021-02-08 07:29:41

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!