您的位置:首页 > 其它

GetLastError使用以及打印输出方法

2016-04-20 09:43 851 查看
GetLastError()返回的只是一个双字节数值(DWORD),但从双字节数无法直接知道错误出处,除非你把错误代码及其含义都记住了(呵呵,一万多个呢...),有个简单输出的方法如下:

#include <windows.h>
#include <strsafe.h>
 
void ErrorExit(LPTSTR lpszFunction) 

    // Retrieve the system error message for the last-error code
 
    LPVOID lpMsgBuf;
    LPVOID lpDisplayBuf;
    DWORD dw = GetLastError(); 
 
    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | 
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dw,
        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),
        TEXT("%s failed with error %d: %s"), 
        lpszFunction, dw, lpMsgBuf); 
    MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK); 
 
    LocalFree(lpMsgBuf);
    LocalFree(lpDisplayBuf);
    ExitProcess(dw); 
}
 
void main()
{
    // Generate an error
 
    if(!GetProcessId(NULL))
        ErrorExit(TEXT("GetProcessId"));
}

这样就能直接打印出错误原因,而不是DWORD值了。此段代码想放在那里就放在那里。

具体的错误代码及其含义请看 :http://www.seacha.com/article.php/knowledge/windows/mfc/2011/0423/335.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: