通过psapi.dll调用GetModuleFileNameEx不起作用,但为什么?

Pet*_*r.O 0 c++ dll

我正在使用没有完整功能的MinGW.例如.它没有wchar_t流支持.我已经设法通过编写一组迷你操纵器(下面的代码中的wcusT())来解决这个问题.但是我发现我再次遇到了GetModuleFileNameEx.我无法原生运行GetModuleFileNameEx()此函数已定义<psapi.h>,但似乎没有任何内容可以链接到.这是我的第一个问题:可以/确实/是MinGW能够运行GetModuleFileNameEx吗?我需要做什么?我错过了一些简单的事吗?作为一种解决方法,我试图通过调用它在Windows system32文件夹中的dll(psapi.dll)来间接运行它......但是出了点问题.我还有另一个禁区.我对以下代码的任何评论表示感谢..谢谢

int WINAPI WinMain (HINSTANCE hThisInstance, HINSTANCE hPrevInstance, LPSTR lpszArgument, int nCmdShow)
{ /// typedef and load a dll function
  /// ===============================
  typedef DWORD (__stdcall *foo)(HANDLE, HMODULE, LPTSTR, DWORD);
  LPTSTR  ptcPSAPI_DLL = _T("C:\\WINDOWS\\system32\\psapi.dll");
  HMODULE   hPSAPI_DLL = LoadLibrary(ptcPSAPI_DLL);
  if( !hPSAPI_DLL ) 
  { std::cout<<"ERROR: Failed to load "<<wcusT(ptcPSAPI_DLL)<<std::endl;
    return 1;
  }
  foo GetModFnEx=(foo)GetProcAddress(hPSAPI_DLL,
                  #ifdef  UNICODE
                         "GetModuleFileNameExW");
                  #else
                         "GetModuleFileNameExA");
                  #endif

  /// call the dll library function
  /// =============================
  HWND   hWndNPP = FindWindow(_T("Notepad++"),NULL); // the window calass name
  TCHAR  ytcMFqFn[FILENAME_MAX]; // the buffer for the file name
  DWORD  dwBytes = (GetModFnEx)( hWndNPP, NULL, ytcMFqFn, sizeof(ytcMFqFn) );  
  DWORD  dwError = GetLastError();

  std::cout<<wcusT(_T("hWndNPP  "))<<"="<<hWndNPP        <<"="<<std::endl;
  std::cout<<wcusT(_T("ytcMFqFn "))<<"="<<wcusT(ytcMFqFn)<<"="<<std::endl;
  std::cout<<wcusT(_T("dwBytes  "))<<"="<<dwBytes        <<"="<<std::endl;
  std::cout<<wcusT(_T("dwError  "))<<"="<<dwBytes        <<"="<<std::endl;
  return 0;

  // Output ===============
  // SBCS 
  //   hWndNPP  =0x320606=
  //   ytcMFqFn ==
  //   dwBytes  =0=
  //   dwError  =0=
  // UNICODE
  //   h W n d N P P     =0x320606=
  //   y t c M F q F n   =(?æ|? =
  //   d w B y t e s     =0=
  //   d w E r r o r     =0=
  //  ======================
Run Code Online (Sandbox Code Playgroud)

Gre*_*jan 5

您的GetModuleFileNameEx调用不正确

HWND   hWndNPP = FindWindow(_T("Notepad++"),NULL); 
DWORD  dwBytes = (GetModFnEx)( hWndNPP // this is ment to be a process handle, not a HWND
  , NULL, ytcMFqFn, sizeof(ytcMFqFn) );
Run Code Online (Sandbox Code Playgroud)

GetModuleFileNameEx上的MSDN doc

您可以尝试使用以下方法之一获取进程句柄

::GetWindowThreadProcessId(hWnd, &dwProcessID);
HANDLE hProcess = ::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, dwProcessID);

// also in PSAPI - EnumProcesses will return an array of app process ids
(BOOL(WINAPI *)(DWORD *,DWORD, DWORD *)) GetProcAddress( psapi, "EnumProcesses" );
Run Code Online (Sandbox Code Playgroud)