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 );
相關文章
相關標籤/搜索