错误信息提示宏 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. }   

 

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