《Windows核心编程》摘录_程序错误代码查看

void seeLastError(DWORD ERRORNO)
{
	HLOCAL hlocal=NULL;
	DWORD systemLocal=MAKELANGID(LANG_NEUTRAL,SUBLANG_NEUTRAL);

	//Get the error code's textual description
	BOOL fOk = FormatMessage(
		FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS
		|FORMAT_MESSAGE_ALLOCATE_BUFFER,
		NULL,ERRORNO,systemLocal,
		(PTSTR)&hlocal,0,NULL);

	if (!fOk)
	{
		//Is it a network-related error
		HMODULE hDll=LoadLibraryEx(_T("netmsg.dll"),NULL,
			DONT_RESOLVE_DLL_REFERENCES);
		if (hDll!=NULL)
		{
			fOk=FormatMessage(
				FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS
				|FORMAT_MESSAGE_ALLOCATE_BUFFER,
				hDll,ERRORNO,systemLocal,
				(PTSTR)&hlocal,0,NULL);
			FreeLibrary(hDll);
		}
	}
	if (hlocal!=NULL)
	{
		AfxMessageBox((PCTSTR)LocalLock(hlocal));
		LocalFree(hlocal);
	}
	else
	{
		AfxMessageBox(_T("未知错误类型!"));
	}
}

上面函数传递一个DWORD类型的错误代码给seeError函数,通过调用该函数来将错误代码ERRORNO转换成WinError.h中的消息文本,并通过当前机器的本地语言(英语、汉语等)输出。

对以上代码解释如下:

1.HLOCAL数据类型

Handle to a local memory block.

This type is declared in WinDef.h as follows:

打印
typedef HANDLE HLOCAL;
2.核心函数FormatMessage

DWORD WINAPI FormatMessage(
  __in      DWORD dwFlags,
  __in_opt  LPCVOID lpSource,
  __in      DWORD dwMessageId,
  __in      DWORD dwLanguageId,
  __out     LPTSTR lpBuffer,
  __in      DWORD nSize,
  __in_opt  va_list *Arguments
);
 
参数:__in      DWORD dwFlags:解析lpSource的格式标志;
 __in_opt  LPCVOID lpSource:定义Message的出处,只有在dwFlags的值是FORMAT_MESSAGE_FROM_HMODULE或FORMAT_MESSAGE_FROM_STRING的时候才有作用
 __in      DWORD dwMessageId:消息Id
  __in      DWORD dwLanguageId:语言Id
  __out     LPTSTR lpBuffer:接收消息描述的缓存区;
  __in      DWORD nSize:缓存区的长度
最后一个看MSDN吧,是个站位符的标志参数。



你可能感兴趣的:(Windows多线程)