api调用错误诊断宏,对GetLastError()函数的封装,并解析错误
从网上找的版本并进行了部分修改
/* * MtVerify.h * * The function PrintError() is marked as __inline so that it can be * included from one or more C or C++ files without multiple definition * errors. * To use the PrintError() in an application, it should be taken out, * placed in its own source file, and the "__inline" declaration removed * so the function will be globally available. * [Modified by thinkhy 10/01/04] ... * [Modified by thinkhy 10/01/07] Added function Myverify. */ #pragma comment( lib, "USER32" ) #define MTASSERT(a) _ASSERTE(a) #ifdef _DEBUG #define MTVERIFY(a) MyVerify(a,_T(#a)) #else #define MTVERIFY(f) (( void )(f)) #endif __inline void PrintError(LPTSTR filename, int lineno, LPTSTR lpszFunc, DWORD errnum) { LPTSTR lpBuffer; TCHAR errbuf[ 256 ]; #ifdef _WINDOWS TCHAR modulename[MAX_PATH]; #else // _WINDOWS DWORD numread; #endif // _WINDOWS FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL , errnum, LANG_NEUTRAL, (LPTSTR)&lpBuffer, // 这个参数很变态! [Commented by thinkhy 10/01/04] 0 , NULL ); wsprintf(errbuf, _T("Failed at Line: %d in File: %s Function: %s Reason: %s"), lineno, filename, lpszFunc, lpBuffer); #ifndef _WINDOWS WriteFile(GetStdHandle(STD_ERROR_HANDLE), errbuf, strlen(errbuf), &numread, FALSE ); Sleep( 3000 ); #else GetModuleFileName( NULL , modulename, MAX_PATH); MessageBox( NULL , errbuf, modulename, MB_ICONWARNING|MB_OK|MB_TASKMODAL|MB_SETFOREGROUND); #endif // exit(EXIT_FAILURE); return ; } __inline BOOL MyVerify(BOOL what,LPTSTR lpszFunc) { #ifdef _DEBUG if (!what) PrintError(_T( __FILE__ ), __LINE__ , lpszFunc,GetLastError()); #endif return what; }
WriteFile(GetStdHandle(STD_ERROR_HANDLE), errbuf, strlen(errbuf), &numread, FALSE ); //错误输出到console窗口
GetStdHandle它用于从一个特定的标准设备(标准输入、标准输出或标准错误)中取得一个句柄。
事例如下:
#include <windows.h> //GetStdHandle和SetConsoleTextAttribute在头文件windows.h中 #include <iostream> using namespace std; void SetColor(unsigned short ForeColor=3,unsigned short BackGroundColor=0) //给参数默认值,使它 //可以接受0/1/2个参数 { HANDLE hCon = GetStdHandle(STD_OUTPUT_HANDLE); //本例以输出为例 SetConsoleTextAttribute(hCon,ForeColor|BackGroundColor); } int main() { SetColor(); std::cout<<"Hello world!"<<endl; SetColor(40,30); std::cout<<"Hello world!"<<endl; std::cout<<"Hello world!"<<endl; getchar(); return 0; }