Windows 2008 R2Win64Windows 2008Win8DLLWindows 7Windows 2003VC++Win32Windows 2000Windows XPMFCBeginnerIntermediateDevWindowsC++
Get Windows Win32 Error Text - Simplified





5.00/5 (2 votes)
Getting the text of Win32 Error codes for 99% of cases.
This code gets Win32 error text. It is written to be read and understood on the first pass. Its arbitrary use of a static buffer is simply to not force one to remember to free the text it returns. It does sacrifice thread safety. It is also written to be a candidate for wrapping in __try/__except as well as try/catch exception handing. The use of objects such as CString would inhibit __try/__except vis-a-vis stack unwinding. Hopefully it's hard to break and easy to change.
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <conio.h>
// In Visual Studio, in Project > Properties > General > Character Set: use 'Not Set' or 'Multi-Byte'
char *GetErrorText(DWORD dwCode)
{
static char buff[2000] // Longest is 403 bytes, but memory is cheap.
memset(buff,0,sizeof(buff));
char *pmsg;
SetLastError(0);
int nbytes = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM, // formatting options flag
NULL, // not a source DLL or format string
dwCode, // returned by GetLastError()
MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),
(LPTSTR)&pmsg, // var to recv alloc'd buffer address
sizeof(buff)-2,NULL);
DWORD dw = GetLastError();
if (dw==0) // NO_ERROR, originally defined as ERROR_SUCCESS
{ // usually ERROR_INVALID_PARAMETER (87L) ' The parameter is incorrect.'
strcpy_s(buff,pmsg);
LocalFree((HLOCAL)pmsg); // Free pmsg after copying to buff[]
}
return buff;
}
int main()
{
for (int code=0; code<2000000; code++)
{
-
if (strlen(msg))
{
printf("Win32 Code %3d: %s", code, msg); // Already has <CR><LF> on end
// Sleep(20); // uncomment to see it scroll past
}
}
// Will keep the console up until you press a key.
puts("\nPress any key to continue....");
while (!_kbhit()) Sleep(10);
}