Blog / Home
About
Media Gallery

Welcome
to
Thronic.com

ժʝ_

Win32 GetLastError() Example


Retrieving and formatting a related system message for a GetLastError() error code.
Used while working on Win32 applications in Visual Studio 2017 (Visual C++).

C++
#include <Windows.h>
#include <string>

void GetError(std::string lpszFunction)
{
	int err = GetLastError();
	std::string lpDisplayBuf;
	char* lpMsgBuf;

	FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
		FORMAT_MESSAGE_FROM_SYSTEM |
		FORMAT_MESSAGE_IGNORE_INSERTS,
		NULL,
		err,
		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
		(LPSTR)&lpMsgBuf,
		0,
		NULL);

	lpDisplayBuf.append("("+ std::to_string(err) +") ");
	lpDisplayBuf.append(lpMsgBuf);
	MessageBox(NULL, lpszFunction.c_str(), lpDisplayBuf.c_str(), MB_OK | MB_ICONINFORMATION);
}


A more C oriented way ...
#include <Windows.h>
#include <strsafe.h>

void GetError(LPCTSTR lpszFunction)
{
	DWORD err = GetLastError();
	LPVOID lpMsgBuf, lpDisplayBuf;

	FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
		FORMAT_MESSAGE_FROM_SYSTEM |
		FORMAT_MESSAGE_IGNORE_INSERTS,
		NULL,
		err,
		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
		(LPTSTR)&lpMsgBuf,
		0,
		NULL);

	lpDisplayBuf = (LPVOID)LocalAlloc(
		LMEM_ZEROINIT,
		(lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR)
	);
	
	StringCchPrintf(
		(STRSAFE_LPWSTR)lpDisplayBuf,
		LocalSize(lpDisplayBuf) / sizeof(TCHAR),
		L"%s failed with error %d: %s",
		lpszFunction, err, lpMsgBuf
	);

	MessageBox(NULL, (LPCTSTR)lpDisplayBuf, L"Error", MB_OK | MB_ICONINFORMATION);
	LocalFree(lpMsgBuf);
}

int main()
{
	GetError(L"OpenProcess()");
	exit(0);
}



Original Post: Jan 27th, '22 19:16 CET.
Updated: Jan 27th, '22 19:17 CET.

C/C++
π