秋梦无痕

一场秋雨无梦痕,春夜清风冻煞人。冬来冷水寒似铁,夏至京北蟑满城。

Avatar

格式化输出错误信息

格式化输出错误信息的函数:

void FormatErrorMessage(DWORD dwError, LPTSTR * lpszMessage) {
BOOL bRet = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
NULL, dwError, MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED),
(LPTSTR)lpszMessage, 0, NULL);
// 此处lpszMessage内存由LocalAlloc得到,需要用LocalFree释放。
if(bRet) {
return;
}

HMODULE hDll = LoadLibraryEx(_T("netmsg.dll"), NULL, DONT_RESOLVE_DLL_REFERENCES);
if (NULL == hDll) {
return;
}
FormatMessage(FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_FROM_SYSTEM,
hDll, dwError, MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED),
(LPTSTR)lpszMessage,0, NULL);
FreeLibrary(hDll);
}


使用方法:

void main(int argc, char* argv[]) {
if(argc != 2) {
printf(_T("Usage:\n\t%s dwErrorID"), argv[0]);
return;
}
LPTSTR lpszMessage = NULL;
DWORD dwError = _atoi64(argv[1]);
FormatErrorMessage(dwError, &lpszMessage);
if(lpszMessage != NULL) {
printf(_T("Error %ld: %s"), dwError, lpszMessage);
LocalFree(lpszMessage);
} else {
printf(_T("Error %ld: 未知错误"), dwError);
}
}

评论已关闭