본문 바로가기
프로그래밍/C, C++

MFC - GetLastError()에 해당하는 메세지 출력

by 꾸션 2015. 2. 9.

GetLastError에 해당하는 메세지 얻어오기

LPVOID lpMsgBuf = NULL;
CString strMsg;

FormatMessage(
    FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
    NULL,
    GetLastError(),
    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
    (LPTSTR)&lpMsgBuf,
    0,
    NULL);

if (!lpMsgBuf)
{
  strMsg = (LPCTSTR)lpMsgBuf;
  LocalFree(lpMsgBuf);
}

이를 토대로 함수를 만들어 보았습니다.

Made by 꾸션

 

헤더

CString GetErrorDescription(DWORD dwLastErrorCode);
CString GetDetailErrorMessage(DWORD dwErrorCode, CString strErrorDescription, CString& strFile, DWORD& dwLineNo);
void DetailErrorMessageBox(DWORD dwLastErrorCode, CString strFile, DWORD dwLineNo, UINT uMB_IconButton /*= MB_OK*/);

 

소스


CString GetErrorDescription(DWORD dwLastErrorCode)
{
  CString strLastErrorDescription;
  LPVOID lpErrorDescription = NULL;

  FormatMessage(
      FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
      NULL,
      dwLastErrorCode,
      MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
      (LPTSTR)&lpErrorDescription,
      0,
      NULL);

  if (!lpErrorDescription)
  {
    strLastErrorDescription = (LPCTSTR)lpErrorDescription;
    LocalFree(lpErrorDescription);
  }

  return strLastErrorDescription;
}

CString GetDetailErrorMessage(DWORD dwErrorCode, CString strErrorDescription, CString &strFile, DWORD &dwLineNo)
{
  CString strErrorMessage;
  COleDateTime datetime = COleDateTime::GetCurrentTime();

  strErrorMessage.Format(
      _T("Date Time: %s\n")
      _T("ErrorCode: %d\n\n")
      _T("%s\n\n")
      _T("File: %s\n")
      _T("Line: %d"),
      datetime.Format(),
      dwErrorCode,
      strErrorDescription,
      strFile,
      dwLineNo);

  return strErrorMessage;
}

void DetailErrorMessageBox(DWORD dwLastErrorCode, CString strFile, DWORD dwLineNo, UINT uMB_IconButton /*= MB_OK*/)
{
  CString strErrorDescription = GetErrorDescription(dwLastErrorCode);
  CString strDetailErrorMessage = GetDetailErrorMessage(dwLastErrorCode, strErrorDescription, strFile, dwLineNo);

  ::AfxMessageBox(strDetailErrorMessage, uMB_IconButton);
}

 

사용

DetailErrorMessageBox(GetLastError(), _T(__FILE__), __LINE__);

 

반응형

댓글