From dc282b6ab5cc234ab9ba7c1605ac7e292842dacd Mon Sep 17 00:00:00 2001 From: BlackMark Date: Sun, 5 Jul 2020 17:38:15 +0200 Subject: [PATCH] Implemented windows error formatting --- AdaptiveBrightness/monitor_control_win.cpp | 38 +++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/AdaptiveBrightness/monitor_control_win.cpp b/AdaptiveBrightness/monitor_control_win.cpp index 9db8da7..b3c4950 100644 --- a/AdaptiveBrightness/monitor_control_win.cpp +++ b/AdaptiveBrightness/monitor_control_win.cpp @@ -2,19 +2,55 @@ #ifdef _MSC_VER + #include + #include #include #include + #include + #include "log_tr.hpp" namespace detail { +template +struct always_false : std::false_type { +}; + +template +inline constexpr auto always_false_v = always_false::value; + +template +static QString fromTchar(T* tString) +{ + if constexpr(std::is_same_v) { + return QString().fromLocal8Bit(tString).trimmed(); + } + else if constexpr(std::is_same_v) { + return QString().fromWCharArray(tString).trimmed(); + } + else { + static_assert(always_false_v, "Unknown TCHAR type"); + } +} + static QString getLastErrorString() { DWORD lastErrorId = GetLastError(); - return {}; + TCHAR* msgBuf; + const auto formatFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; + + if(FormatMessage(formatFlags, nullptr, lastErrorId, 0, reinterpret_cast(&msgBuf), 0, nullptr) == 0) { + return "FormatMessage failed"; + } + + const auto lastErrorString = fromTchar(msgBuf); + + LocalFree(msgBuf); + + return lastErrorString; } static BOOL enumMonitorsCallback(HMONITOR hMonitor, [[maybe_unused]] HDC hDC, [[maybe_unused]] LPRECT lpRect, LPARAM lParam)