Last active
May 16, 2018 18:12
-
-
Save daxliar/495ba681b2dc341f9a7f56c418e58c9f to your computer and use it in GitHub Desktop.
Create a string with last error message
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Needs Windows constant and type definitions | |
#include <windows.h> | |
#include <string> | |
// Create a string with last error message | |
std::string GetLastErrorStdStr() | |
{ | |
DWORD error = GetLastError(); | |
if (error) | |
{ | |
LPVOID lpMsgBuf; | |
DWORD bufLen = FormatMessage( | |
FORMAT_MESSAGE_ALLOCATE_BUFFER | | |
FORMAT_MESSAGE_FROM_SYSTEM | | |
FORMAT_MESSAGE_IGNORE_INSERTS, | |
NULL, | |
error, | |
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), | |
(LPTSTR) &lpMsgBuf, | |
0, NULL ); | |
if (bufLen) | |
{ | |
LPCSTR lpMsgStr = (LPCSTR)lpMsgBuf; | |
std::string result(lpMsgStr, lpMsgStr+bufLen); | |
LocalFree(lpMsgBuf); | |
return result; | |
} | |
} | |
return std::string(); | |
} | |
std::wstring GetLastErrorStdStrW() | |
{ | |
DWORD error = GetLastError(); | |
if (error) | |
{ | |
LPVOID lpMsgBuf; | |
DWORD bufLen = FormatMessageW( | |
FORMAT_MESSAGE_ALLOCATE_BUFFER | | |
FORMAT_MESSAGE_FROM_SYSTEM | | |
FORMAT_MESSAGE_IGNORE_INSERTS, | |
NULL, | |
error, | |
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), | |
(LPTSTR) &lpMsgBuf, | |
0, NULL ); | |
if (bufLen) | |
{ | |
LPCWSTR lpMsgStr = (LPCWSTR)lpMsgBuf; | |
std::wstring result(lpMsgStr, lpMsgStr+bufLen); | |
LocalFree(lpMsgBuf); | |
return result; | |
} | |
} | |
return std::wstring(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment