写个实用的小类,用于输出win的错误码文本信息,因为直接使用FormatMessage确实会繁琐一点。所以将类设计成
/// 实现
// 示例
函数对象的形式。默认以英文、方式输出,省去了自己设定语言类别的麻烦。当然自己可以设定语言类别(参看
MSDN)。
/// 声明
- /**
- * @author roofalison
- * @date 2008-09-24-14:03
- * @class windows错误码显示类
- */
- #ifndef WIN_ERR_MESSAGE_H
- #define WIN_ERR_MESSAGE_H
- #include <windows.h>
- #include <string>
- using std::string;
- class WinErrMessage
- {
- public :
- WinErrMessage(
- DWORD dwErrCode = 0,
- DWORD dwLanguageID = MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US) );
- ~WinErrMessage();
- void setErrCode(DWORD dwErrCode);
- void setLangID(DWORD dwLangID);
- operator string();
- private :
- DWORD m_dwErrCode;
- DWORD m_dwLanguageID;
- bool m_bChanged;
- string m_strErrMessage;
- };
- #endif
- /**
- * @author roofalison
- * @date 2008-09-24-14:03
- */
- #include "WinErrMessage.h"
- WinErrMessage::WinErrMessage(DWORD dwErrCode, DWORD dwLanguageID)
- : m_dwErrCode(dwErrCode), m_dwLanguageID(dwLanguageID), m_bChanged(true)
- {
- }
- WinErrMessage::~WinErrMessage()
- {
- }
- void WinErrMessage::setErrCode(DWORD dwErrCode)
- {
- if (m_dwErrCode != dwErrCode)
- {
- m_bChanged = true;
- m_dwErrCode = dwErrCode;
- }
- }
- void WinErrMessage::setLangID(DWORD dwLanguageID)
- {
- if (m_dwLanguageID != dwLanguageID)
- {
- m_bChanged = true;
- m_dwLanguageID = dwLanguageID;
- }
- }
- WinErrMessage::operator string()
- {
- if (m_bChanged)
- {
- HLOCAL hLocal = NULL;
- BOOL bOK = ::FormatMessage(
- FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
- NULL,
- m_dwErrCode,
- m_dwLanguageID,
- (LPTSTR)&hLocal,
- 0,
- NULL
- );
- m_strErrMessage = bOK ? string(static_cast<const char*>(hLocal)) : "";
- if (NULL != hLocal)
- {
- ::LocalFree(hLocal);
- }
- m_bChanged = false;
- }
- return m_strErrMessage;
- }
- #include "WinErrMessage.h"
- #include <iostream>
- #include <windows.h>
- using namespace std;
- int main()
- {
- WinErrMessage win(0x32);
- cout << static_cast<string>(win) << endl;
- win.setErrCode(0x11);
- cout << static_cast<string>(win) << endl;
- win.setLangID( MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED) );
- cout << static_cast<string>(win) << endl;
- string str = win;
- cout << str << endl;
- cout << static_cast<string>(WinErrMessage(0x11)) << endl;
- return 0;
- }