FormatMessageフォーマットエラーメッセージ


// ErrorMsg.h
#pragma once

class CErrorMsg
{
public:
	CErrorMsg(void);
	virtual ~CErrorMsg(void);

public:
	DWORD GetLastError(DWORD dwErrorId, LPTSTR lpszError, DWORD dwLength);

private:
	LPCTSTR m_pErrorMsg;
	HLOCAL m_hLocal;
};

// ErrorMsg.cpp
#include "StdAfx.h"
#include "ErrorMsg.h"


CErrorMsg::CErrorMsg(void) : m_pErrorMsg(NULL), m_hLocal(NULL)
{
}


CErrorMsg::~CErrorMsg(void)
{
	if(NULL != m_hLocal)
	{
		LocalFree(m_hLocal);
		m_hLocal = NULL;
	}
	m_pErrorMsg = NULL;
}

DWORD CErrorMsg::GetLastError(DWORD dwErrorId, LPTSTR lpszError, DWORD dwLength)
{
	if(NULL == m_pErrorMsg)
	{
		if(NULL != m_hLocal)
		{
			LocalFree(m_hLocal);
			m_hLocal = NULL;
		}

		if(!FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ALLOCATE_BUFFER,
			NULL, dwErrorId, MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), (PTSTR)&m_hLocal, 0, NULL))
		{
			return 0;
		}

		if(NULL == m_hLocal)
		{
			return 0;
		}
		m_pErrorMsg = (PCTSTR)LocalLock(m_hLocal);
	}

	if(NULL == lpszError)
	{
		if(NULL != m_pErrorMsg)
		{
			dwLength = _tcslen(m_pErrorMsg) + 1;
		}
		else
		{
			dwLength = 0;
		}
	}
	else
	{
		_tcscpy_s(lpszError, dwLength, m_pErrorMsg);
		m_pErrorMsg = NULL;
		if(NULL != m_hLocal)
		{
			LocalFree(m_hLocal);
			m_hLocal = NULL;
		}
	}	
	return dwLength;
}

// Test code :
#include "stdafx.h"
#include "ErrorMsg.h"

int _tmain(int argc, _TCHAR* argv[])
{
	CErrorMsg err;
	DWORD dwLength = 0;
	TCHAR* pBuf = NULL;
	dwLength = err.GetLastError(2, pBuf, 0);
	if(0 != dwLength)
	{
		pBuf = new TCHAR[dwLength];
	}

	if(NULL != pBuf)
	{
		err.GetLastError(2, pBuf, dwLength);
		_tprintf(_T("%s
"), pBuf); } delete[] pBuf; pBuf = NULL; return 0; }