This is a mirror of official site: http://jasper-net.blogspot.com/

Using FormatMessage

| Sunday, June 6, 2010
The FormatMessage API call is very powerful, and particularly useful for issuing all kinds of messages. This is not intended to be a full tutorial on using FormatMessage, but simply an example of one of the most effective uses of the the call. There is nothing more offensive than being presented with a message like the one below:

This is incomprehensible. The file cannot be opened. Why? For that matter, what file? The name the user types in is only part of the filename context; the rest relies on the current directory, which may not be what the user thinks it is. Errors like this generate unnecessary support calls to tech support departments, and consume a lot of time of the technical support people trying to determine what has gone wrong. A muchbetter example of an error message is the next one. It tells what the application-level error is, what file was being considered, and the description of the error code.

In this case, I had created a read-only file junk.txt to induce the error on a Save command.

CString ErrorString(DWORD err)
   {
    CString Error;
    LPTSTR s;
    if(::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
           FORMAT_MESSAGE_FROM_SYSTEM,
           NULL,
           err,
           0,
           (LPTSTR)&s,
           0,
           NULL) == 0)
   { /* failed */
    // Unknown error code %08x (%d)

    CString fmt;
    CString t;
    fmt.LoadString(IDS_UNKNOWN_ERROR);
    t.Format(fmt, err, LOWORD(err));
    Error = t;
   } /* failed */
    else
   { /* success */
    LPTSTR p = _tcschr(s, _T('\r'));
    if(p != NULL)
       { /* lose CRLF */
        *p = _T('\0');
       } /* lose CRLF */
    Error = s;
    ::LocalFree(s);
   } /* success */
    return Error;
   } // ErrorString

Read more: Codeproject

Posted via email from jasper22's posterous

0 comments: