Process.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #include "il2cpp-config.h"
  2. #if IL2CPP_TARGET_WINDOWS_DESKTOP || IL2CPP_TARGET_WINDOWS_GAMES
  3. #include "WindowsHelpers.h"
  4. #include <Psapi.h>
  5. #include "os/Process.h"
  6. struct ProcessHandle
  7. {
  8. HANDLE handle;
  9. };
  10. namespace il2cpp
  11. {
  12. namespace os
  13. {
  14. int Process::GetCurrentProcessId()
  15. {
  16. return ::GetCurrentProcessId();
  17. }
  18. utils::Expected<ProcessHandle*> Process::GetProcess(int processId)
  19. {
  20. return (ProcessHandle*)OpenProcess(PROCESS_ALL_ACCESS, TRUE, processId);
  21. }
  22. void Process::FreeProcess(ProcessHandle* handle)
  23. {
  24. ::CloseHandle((HANDLE)handle);
  25. }
  26. utils::Expected<std::string> Process::GetProcessName(ProcessHandle* handle)
  27. {
  28. const size_t bufferLength = 256;
  29. WCHAR buf[bufferLength];
  30. DWORD length = ::GetModuleBaseName((HANDLE)handle, NULL, buf, bufferLength);
  31. if (length == 0)
  32. return std::string();
  33. char multiByteStr[bufferLength];
  34. size_t numConverted = wcstombs(multiByteStr, buf, bufferLength);
  35. if (numConverted <= 0)
  36. return std::string();
  37. return std::string(multiByteStr, numConverted);
  38. }
  39. #if IL2CPP_TARGET_WINDOWS_GAMES
  40. intptr_t Process::GetMainWindowHandle(int32_t pid)
  41. {
  42. return 0;
  43. }
  44. #else
  45. typedef struct
  46. {
  47. DWORD pid;
  48. HWND hwnd;
  49. } EnumWindowsArgs;
  50. static BOOL STDCALL Il2CppEnumWindowsCallback(HWND hwnd, LPARAM lparam)
  51. {
  52. EnumWindowsArgs* args = (EnumWindowsArgs*)lparam;
  53. DWORD pid = 0;
  54. GetWindowThreadProcessId(hwnd, &pid);
  55. if (pid != args->pid || GetWindow(hwnd, GW_OWNER) != NULL || !IsWindowVisible(hwnd)) return TRUE;
  56. args->hwnd = hwnd;
  57. return FALSE;
  58. }
  59. intptr_t Process::GetMainWindowHandle(int32_t pid)
  60. {
  61. EnumWindowsArgs args = { (DWORD)pid, 0 };
  62. EnumWindows(Il2CppEnumWindowsCallback, (LPARAM)&args);
  63. return (intptr_t)args.hwnd;
  64. }
  65. #endif
  66. }
  67. }
  68. #endif // IL2CPP_TARGET_WINDOWS_DESKTOP || IL2CPP_TARGET_WINDOWS_GAMES