標籤:
Windows編程有時會因為調用函數而產生錯誤,調用GetLastError()函數可以得到錯誤碼。如果錯誤碼為0,說明沒有錯誤;如果錯誤碼不為0,則說明存在錯誤。
而錯誤碼不方便編程人員或使用者直觀理解到底發生了什麼錯誤。Visual Studio 2015(或之前的版本)提供了“錯誤尋找”的外部工具,輸入錯誤碼即可以查看到底發生了什麼錯誤。
如果想在程式碼中查看錯誤碼對應的錯誤資訊,可以編寫如下函數來實現:
#include<iostream>#include<Windows.h>using namespace std;void winerr( );int main(int argc, char* argv[]){ system("haha"); winerr(); system("pause"); return 0;}void winerr( ){ char* win_msg = NULL; DWORD code = GetLastError(); if (code == 0) { cout << "error "<<code<<":No error!\n"; return; } else { //擷取錯誤資訊 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&win_msg, 0, NULL); if (win_msg != NULL) { cout << "error " << code <<":" << win_msg << endl; LocalFree(win_msg); } } //為了使得該函數的調用不影響後續函數調用GetLastError()函數的結果 SetLastError(code);}
測試結果:
Windows API 編程----將錯誤碼轉換成錯誤描述資訊