Last active
February 22, 2020 10:25
-
-
Save nibasya/8e745b45c64b9294667171888fa571b7 to your computer and use it in GitHub Desktop.
Get CString object from GetLastError information
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
#include "stdafx.h" | |
#include "CGetLastError.h" | |
void main() | |
{ | |
// snip | |
SetLastError(111); // create a error 111 (ERROR_BUFFER_OVERFLOW) for demo | |
// Message Box with a text associated to 111(ERROR_BUFFER_OVERFLOW) appears. | |
// In English: "The file name is too long." | |
// In Japanese: "ファイル名が長すぎます。" | |
MessageBox(GetLastErrorToString()); | |
// snip | |
SetLastError(111); // create a error 111 (ERROR_BUFFER_OVERFLOW) for demo | |
// Show error message in output window of Visual Studio | |
GetLastErrorToString().CreateMsg(); | |
} |
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
#include "pch.h" // enable for visual studio version >= 2019 | |
// #include "stdafx.h" // enable for visual studio version < 2019 | |
#include "GetLastErrorToString.h" | |
GetLastErrorToString::operator CString() | |
{ | |
CreateMsg(); | |
return m_msg; | |
} | |
GetLastErrorToString::operator LPCTSTR() | |
{ | |
CreateMsg(); | |
return (LPCTSTR)m_msg; | |
} | |
void GetLastErrorToString::CreateMsg() | |
{ | |
LPTSTR *buff; | |
m_ID = GetLastError(); | |
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, m_ID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&buff, 10, NULL); | |
m_msg.Format(_T("%s"), buff); | |
LocalFree(buff); | |
#ifdef UNICODE | |
_RPTW2(_CRT_WARN, _T("Error ID: %d Msg: %s"), m_ID, m_msg); | |
#else | |
_RPT2(_CRT_WARN, _T("Error ID: %d Msg: %s"), m_ID, m_msg); | |
#endif | |
} |
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
#pragma once | |
class GetLastErrorToString | |
{ | |
public: | |
operator CString(); | |
operator LPCTSTR(); /// <summery>Returns temporary address of message. DO NOT USE FOR LONG TIME, OR COPY DATA IMMEDIATELY.</summery> | |
void CreateMsg(); | |
private: | |
CString m_msg; | |
DWORD m_ID; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment