在Windows API调用之后,如何以文本形式获取最后一个错误消息?
GetLastError()
返回整数值,而不是文本消息。
发布于 2013-06-30 12:32:18
//Returns the last Win32 error, in string format. Returns an empty string if there is no error.
std::string GetLastErrorAsString()
{
//Get the error message ID, if any.
DWORD errorMessageID = ::GetLastError();
if(errorMessageID == 0) {
return std::string(); //No error message has been recorded
}
LPSTR messageBuffer = nullptr;
//Ask Win32 to give us the string version of that message ID.
//The parameters we pass in, tell Win32 to create the buffer that holds the message for us (because we don't yet know how long the message string will be).
size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);
//Copy the error message into a std::string.
std::string message(messageBuffer, size);
//Free the Win32's string's buffer.
LocalFree(messageBuffer);
return message;
}
发布于 2009-09-07 06:21:24
MSDN提供了一些示例代码来演示如何同时使用FormatMessage()
和GetLastError()
:Retrieving the Last-Error Code
发布于 2009-09-07 00:10:38
FormatMessage会将GetLastError(http://msdn.microsoft.com/en-us/library/ms679360(VS.85%29.aspx)'s integer return )转换为文本消息。
https://stackoverflow.com/questions/1387064
复制相似问题