Skip to content

Instantly share code, notes, and snippets.

@nibasya

nibasya/Example.cpp

Last active Feb 22, 2020
Embed
What would you like to do?
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
You can’t perform that action at this time.