Windows错误处理及错误消息文字显示

主要用到两个函数 函数

  1. GetLastError(),返回DWORD是一个32位编号。
  2.  FormatMessage(),将错误代码显示为相应的文本描述。

 Windows函数失败时返回值spa

0或者NULL,所以能够用  if(!res){ ...} 处理错误code

好用的错误通知函数,以如下形式报错:orm

void my_ShowError(DWORD dwErrNo, LPTSTR lpszFunction)
{ 
    // Retrieve the system error message for the last-error code
    LPVOID lpMsgBuf;
    LPVOID lpDisplayBuf;
    
    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | 
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dwErrNo,//
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR) &lpMsgBuf,
        0, NULL );

    // Display the error message and exit the process

    lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, 
        (lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(TCHAR)); 
    StringCchPrintf((LPTSTR)lpDisplayBuf, 
        LocalSize(lpDisplayBuf) / sizeof(TCHAR),
        TEXT("%s failed with error %d: %s"), 
        lpszFunction, dwErrNo, lpMsgBuf); 
    MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK); 

    LocalFree(lpMsgBuf);
    LocalFree(lpDisplayBuf);
//    ExitProcess(dwErrNo);
}
DWORD dwErrNo = GetLastError();
if ( NO_ERROR != dwErrNo ){
    ShowError( dwErrNo, "foobar" );
//    return dwErrNo;
}
LPVOID lpMsgBuf; 
FormatMessage( 
    FORMAT_MESSAGE_ALLOCATE_BUFFER | 
    FORMAT_MESSAGE_FROM_SYSTEM | 
    FORMAT_MESSAGE_IGNORE_INSERTS, 
    NULL, 
    GetLastError(), 
    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
    (LPTSTR) &lpMsgBuf, 
    0, 
    NULL 
    ); 
MessageBox(  (LPCTSTR)lpMsgBuf); 
LocalFree( lpMsgBuf );
相关文章
相关标签/搜索