-
Notifications
You must be signed in to change notification settings - Fork 19
/
FormatMessageWrapper.h
81 lines (70 loc) · 2.54 KB
/
FormatMessageWrapper.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// sktoolslib - common files for SK tools
// Copyright (C) 2012, 2017, 2020-2021 - Stefan Kueng
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software Foundation,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
#pragma once
/**
* A wrapper class for calling the FormatMessage() Win32 function and controlling
* the lifetime of the allocated error message buffer.
*/
class CFormatMessageWrapper
{
private:
LPWSTR buffer;
DWORD result;
void release();
void obtainMessage() { obtainMessage(::GetLastError()); }
void obtainMessage(DWORD errorCode);
public:
CFormatMessageWrapper()
: buffer(nullptr)
, result(0)
{
obtainMessage();
}
CFormatMessageWrapper(DWORD lastError)
: buffer(nullptr)
, result(0)
{
obtainMessage(lastError);
}
~CFormatMessageWrapper() { release(); }
operator LPCWSTR() const { return buffer; }
operator bool() const { return result != 0; }
bool operator!() const { return result == 0; }
LPCWSTR c_str() const { return buffer; }
};
inline void CFormatMessageWrapper::obtainMessage(DWORD errorCode)
{
// First of all release the buffer to make it possible to call this
// method more than once on the same object.
release();
result = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
errorCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
reinterpret_cast<LPWSTR>(&buffer),
0,
nullptr);
}
inline void CFormatMessageWrapper::release()
{
if (buffer != nullptr)
{
LocalFree(buffer);
buffer = nullptr;
}
result = 0;
}