From 68a7ae20e9b99157a5ac8f4ef8ac1e01a214b8eb Mon Sep 17 00:00:00 2001 From: Erich Yu Date: Wed, 28 Aug 2024 10:42:00 +0800 Subject: [PATCH] =?UTF-8?q?=E9=87=8D=E6=9E=84=E8=8E=B7=E5=8F=96=E7=AA=97?= =?UTF-8?q?=E5=8F=A3=E8=BF=9B=E7=A8=8B=E5=8F=A5=E6=9F=84=20(#987)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * refactor getting process handle of window * log errors when failed to get process handle --- src/Magpie.App/ScalingService.cpp | 11 ++--------- src/Shared/Win32Utils.cpp | 14 ++++++++++---- src/Shared/Win32Utils.h | 2 ++ 3 files changed, 14 insertions(+), 13 deletions(-) diff --git a/src/Magpie.App/ScalingService.cpp b/src/Magpie.App/ScalingService.cpp index 05bcedd5..2fb381f3 100644 --- a/src/Magpie.App/ScalingService.cpp +++ b/src/Magpie.App/ScalingService.cpp @@ -342,16 +342,9 @@ 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 失败"); + Logger::Get().Error("GetWndProcessHandle 失败"); return false; } diff --git a/src/Shared/Win32Utils.cpp b/src/Shared/Win32Utils.cpp index 33fdb396..f184b48c 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,16 @@ 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) { + Logger::Get().Error("GetWndProcessHandle 失败"); + return {}; } std::wstring fileName; diff --git a/src/Shared/Win32Utils.h b/src/Shared/Win32Utils.h index 5d03c3dd..b68f0ada 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 GetWndProcessHandle(HWND hWnd) noexcept; + static std::wstring GetPathOfWnd(HWND hWnd) noexcept; static UINT GetWindowShowCmd(HWND hWnd) noexcept;