A function anyone attempting to program applications for Microsoft Windows should be well aware of, since it is most often used to get a slightly less cryptic error message from a cryptic error code. Below is an example of how to retrieve the error message for the last error code and present it in a message box:

LPVOID msg;
 
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL, GetLastError(), 0, (LPTSTR) &msg, 0, NULL);

MessageBox(NULL, msg, "Error!", MB_OK | MB_ICONERROR);

LocalFree(msg);

For more detailed instructions on parameters (languages, message parameters, etc), consult the Windows API helpfiles.

An interesting side note is that if the function fails, it returns zero. In order to determine what went wrong, you must call GetLastError(), and to translate the code you need to call FormatMessage() again. Phew. Let's just hope this function isn't as error prone as Microsoft code seems to be most of the time, or we may just as well go ahead and do a for ( ; ; ) { } right away to spare Billy Boy the trouble.

UPDATE: Long time since I wrote this now, but I still check it for reference. For those programming in .NET, however, there is a way doing this using the .NET classes instead of using the Win32 API through PInvoke:

C#:

string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message;
System.Windows.Forms.MessageBox.Show(errorMessage);

Visual Basic:

Dim errorMessage As String = New Win32Exception(Err.LastDllError).Message
System.Windows.Forms.MessageBox.Show(errorMessage)

Log in or register to write something here or to contact authors.