0
我是Windows API的新手,當我想出如何獲取系統消息代碼描述時,我想知道是否更好,更優雅的方式去做。或者,爲了教育目的,如果通常還有其他方式,則可以使用。Windows API - 將FormatMessage()的結果轉換爲std :: string
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
);
更新的代碼後評論:
std::string bmd2File::getErrorCodeDescription(long errorCode) const throw (bmd2Exception)
{
#ifdef _WIN32
char MessageFromSystem[1024];
bool messageReceived = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
0,
errorCode,
1033, // US English
MessageFromSystem,
1024,
0);
std::ostringstream ostr;
if (!messageReceived)
ostr << "Error code: " << errorCode;
else
ostr << "Error code " << errorCode << " with message: " << MessageFromSystem;
return ostr.str();
#else
#endif
}
OLD CODE
std::string bmd2File::getErrorCodeDescription(long errorCode) const throw (bmd2Exception)
{
#ifdef _WIN32
char MessageFromSystem[1024];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
0,
errorCode,
1033, // US English
MessageFromSystem,
1024,
0);
return std::string(MessageFromSystem);
#else
#endif
}
我看起來像一個菜鳥或者是這個代碼好嗎?
謝謝,我會解決的! –
char數組[1024]怎麼樣?似乎低級別以字節爲單位指定一個char數組,並且只是交叉手指以指望它足夠大。 –
而不是硬編碼緩衝區大小讓函數爲您分配它。您可以按位或ORF FORMAT_MESSAGE_ALLOCATE_BUFFER到該函數的第一個參數。 – Vishal