FormatMessage示例

Windows核心编程chapter one

#include "stdafx.h"
#include <windows.h>
#include <windowsx.h>
#include "Resource.h"
#include "MainDlg.h"

BOOL WINAPI Main_Proc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	switch(uMsg)
	{
		HANDLE_MSG(hWnd, WM_INITDIALOG, Main_OnInitDialog);
		HANDLE_MSG(hWnd, WM_COMMAND, Main_OnCommand);
		HANDLE_MSG(hWnd,WM_CLOSE, Main_OnClose);
	}

	return FALSE;
}

BOOL Main_OnInitDialog(HWND hwnd, HWND hwndFocus, LPARAM lParam)
{
	return TRUE;
}

void Main_OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify)
{
	switch(id)
	{
	case IDC_BTN_LOOKUP:
		{
			//Get the error code
			DWORD dwError = GetDlgItemInt(hwnd,IDC_ERRORCODE,NULL,FALSE);
			HLOCAL hlocal = NULL; //Buffer that gets the error message string
			DWORD systemLocale = 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,dwError,systemLocale,(PTSTR)&hlocal,0,NULL);

			if (!fOk)
			{
				//Is it a network-related error?
				HMODULE hDll = LoadLibraryEx("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,dwError,systemLocale,(PTSTR)&hlocal,0,NULL);
					FreeLibrary(hDll);
				}
			}

			if (fOk && (hlocal!=NULL))
			{
				SetDlgItemText(hwnd,IDC_TEXTAREA,(PCTSTR)LocalLock(hlocal));
				LocalFree(hlocal);
			}else{
				SetDlgItemText(hwnd,IDC_TEXTAREA,TEXT("No text found for this error number."));
			}

		}
		break;
	default:
		break;
	}
}

void Main_OnClose(HWND hwnd)
{
	EndDialog(hwnd, 0);
}
效果

FormatMessage示例

你可能感兴趣的:(FormatMessage示例)