錯誤信息提示宏 MTVERIFY頭文件 MTVERIFY.H 源代碼

Code:
  1. /**  
  2.  * MtVerify.h  
  3.  *  
  4.  * Error handling for applications in  
  5.  * "Multitheading Applications in Win32"  
  6.  *  
  7.  * The function PrintError() is marked as __inline so that it can be  
  8.  * included from one or more C or C++ files without multiple definition  
  9.  * errors. For the examples in this book, this works fine.  
  10.  * To use the PrintError() in an application, it should be taken out,  
  11.  * placed in its own source file, and the "__inline" declaration removed  
  12.  * so the function will be globally available.  
  13.  */  
  14.   
  15. #pragma comment( lib, "USER32" )   
  16. #include <stdlib.h>   
  17. #include <crtdbg.h>   
  18. #define MTASSERT(a) _ASSERTE(a)   
  19.   
  20. // 宏定義 __FILE__ 與__LINE__都是預處理符號提供錯誤信息的描述   
  21. // 如果a返回FALSE就執行PrintError函數   
  22. #define MTVERIFY(a) if (!(a)) PrintError(#a,__FILE__,__LINE__,GetLastError())   
  23.   
  24. __inline void PrintError(LPSTR linedesc, LPSTR filename, int lineno, DWORD errnum)   
  25. {   
  26.   
  27. LPSTR lpBuffer;   
  28. char errbuf[256];   
  29. #ifdef _WINDOWS   
  30. char modulename[MAX_PATH];   
  31. #else // _WINDOWS   
  32. DWORD numread;   
  33. #endif // _WINDOWS   
  34.   
  35. // 把從GetLastError()返回的錯誤碼轉化爲錯誤信息    
  36. FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER   
  37. | FORMAT_MESSAGE_FROM_SYSTEM,   
  38. NULL,   
  39. errnum,   
  40. LANG_NEUTRAL,   
  41. (LPTSTR)&lpBuffer,   
  42. 0,   
  43. NULL );   
  44.   
  45. wsprintf(errbuf, "/nThe following call failed at line %d in %s:/n/n"  
  46.   " %s/n/nReason: %s/n", lineno, filename, linedesc, lpBuffer);   
  47.   
  48. // 如果是console程序就輸出信息到控制檯上    
  49. #ifndef _WINDOWS   
  50. WriteFile(GetStdHandle(STD_ERROR_HANDLE), errbuf, strlen(errbuf), &numread, FALSE );   
  51.   
  52. // 等待3秒鐘是爲了使用者看到出錯信息   
  53. Sleep(3000);   
  54.   
  55. // 如果是窗口程序就一彈出對話框的形式輸出錯誤信息   
  56. #else   
  57.   
  58. // 當前exe文件的全路徑   
  59. GetModuleFileName(NULL, modulename, MAX_PATH);   
  60. // 置彈出窗口在最上層以免被忽略   
  61. MessageBox(NULL, errbuf, modulename, MB_ICONWARNING|MB_OK|MB_TASKMODAL|MB_SETFOREGROUND);   
  62. #endif   
  63. // 把結束代碼EXIT_FAILURE 交給操作系統   
  64. exit(EXIT_FAILURE);   
  65. }   

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章