From ed5e418f868cc942dca585d9b8eb1952bf8907aa Mon Sep 17 00:00:00 2001 From: Erich Date: Wed, 28 Aug 2024 01:31:39 +0800 Subject: [PATCH] refactor getting process handle of window --- src/Magpie.App/ScalingService.cpp | 10 +--------- src/Shared/Win32Utils.cpp | 13 +++++++++---- src/Shared/Win32Utils.h | 2 ++ 3 files changed, 12 insertions(+), 13 deletions(-) diff --git a/src/Magpie.App/ScalingService.cpp b/src/Magpie.App/ScalingService.cpp index 938bcabf..559017d5 100644 --- a/src/Magpie.App/ScalingService.cpp +++ b/src/Magpie.App/ScalingService.cpp @@ -330,16 +330,8 @@ void ScalingService::_ScaleForegroundWindow() { } static bool GetWindowIntegrityLevel(HWND hWnd, DWORD& integrityLevel) noexcept { - DWORD processId; - if (!GetWindowThreadProcessId(hWnd, &processId)) { - Logger::Get().Win32Error("GetWindowThreadProcessId 失败"); - return false; - } - - wil::unique_process_handle hProc( - OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processId)); + wil::unique_process_handle hProc = Win32Utils::GetWndProcessHandle(hWnd); if (!hProc) { - Logger::Get().Win32Error("OpenProcess 失败"); return false; } diff --git a/src/Shared/Win32Utils.cpp b/src/Shared/Win32Utils.cpp index 33fdb396..df070fd0 100644 --- a/src/Shared/Win32Utils.cpp +++ b/src/Shared/Win32Utils.cpp @@ -34,7 +34,7 @@ std::wstring Win32Utils::GetWndTitle(HWND hWnd) noexcept { return title; } -std::wstring Win32Utils::GetPathOfWnd(HWND hWnd) noexcept { +wil::unique_process_handle Win32Utils::GetWndProcessHandle(HWND hWnd) noexcept { wil::unique_process_handle hProc; if (DWORD dwProcId = 0; GetWindowThreadProcessId(hWnd, &dwProcId)) { @@ -58,10 +58,15 @@ std::wstring Win32Utils::GetPathOfWnd(HWND hWnd) noexcept { Logger::Get().Win32Error("GetProcessHandleFromHwnd 失败"); } } + } - if (!hProc) { - return {}; - } + return hProc; +} + +std::wstring Win32Utils::GetPathOfWnd(HWND hWnd) noexcept { + wil::unique_process_handle hProc = ::GetWndProcessHandle(hWnd); + if (!hProc) { + return {}; } std::wstring fileName; diff --git a/src/Shared/Win32Utils.h b/src/Shared/Win32Utils.h index 5d03c3dd..df35cebb 100644 --- a/src/Shared/Win32Utils.h +++ b/src/Shared/Win32Utils.h @@ -14,6 +14,8 @@ struct Win32Utils { static std::wstring GetWndTitle(HWND hWnd) noexcept; + static wil::unique_process_handle Win32Utils::GetWndProcessHandle(HWND hWnd) noexcept; + static std::wstring GetPathOfWnd(HWND hWnd) noexcept; static UINT GetWindowShowCmd(HWND hWnd) noexcept;