Skip to content

Instantly share code, notes, and snippets.

@nibasya
Last active February 22, 2020 10:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nibasya/8e745b45c64b9294667171888fa571b7 to your computer and use it in GitHub Desktop.
Save nibasya/8e745b45c64b9294667171888fa571b7 to your computer and use it in GitHub Desktop.
Get CString object from GetLastError information
#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();
}
#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
}
#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