GetLastError使用以及打印输出方法
2016-04-20 09:43
851 查看
GetLastError()返回的只是一个双字节数值(DWORD),但从双字节数无法直接知道错误出处,除非你把错误代码及其含义都记住了(呵呵,一万多个呢...),有个简单输出的方法如下:
#include <windows.h>
#include <strsafe.h>
void ErrorExit(LPTSTR lpszFunction)
{
// Retrieve the system error message for the last-error code
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
// Display the error message and exit the process
lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf),
TEXT("%s failed with error %d: %s"),
lpszFunction, dw, lpMsgBuf);
MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
ExitProcess(dw);
}
void main()
{
// Generate an error
if(!GetProcessId(NULL))
ErrorExit(TEXT("GetProcessId"));
}
这样就能直接打印出错误原因,而不是DWORD值了。此段代码想放在那里就放在那里。
具体的错误代码及其含义请看 :http://www.seacha.com/article.php/knowledge/windows/mfc/2011/0423/335.html
#include <windows.h>
#include <strsafe.h>
void ErrorExit(LPTSTR lpszFunction)
{
// Retrieve the system error message for the last-error code
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
// Display the error message and exit the process
lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf),
TEXT("%s failed with error %d: %s"),
lpszFunction, dw, lpMsgBuf);
MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
ExitProcess(dw);
}
void main()
{
// Generate an error
if(!GetProcessId(NULL))
ErrorExit(TEXT("GetProcessId"));
}
这样就能直接打印出错误原因,而不是DWORD值了。此段代码想放在那里就放在那里。
具体的错误代码及其含义请看 :http://www.seacha.com/article.php/knowledge/windows/mfc/2011/0423/335.html
相关文章推荐
- KVC/KVO 监听对象属性变化
- c++中的转码函数
- php json对接app接口
- Django之tag的使用
- 计算器界面
- c++中查询硬件与系统信息api
- 个人对设计模式的理解-->桥接模式
- GPRS网络概述
- Android Studio 快捷键修改
- iOS 初学者学习网站
- CSS3实现32种基本图形
- 初识 iOS 9 中新的联系人框架
- 详解KVO 2 底层概念,手动管理KVO
- 每天laravel-20160720|ScheduleServiceProvid
- 使用行转列实现分房间查询
- (转)nmap速查表v1.0(中文版)
- css 填坑常用代码分享
- 编译csipsimple的native部分
- 使用 Eclipse Memory Analyzer 进行堆转储文件分析
- 大文件远程拷贝方法(10G左右的文件)