程序有的时候要长时间运行,如果中间出现错误,就需要弹出dump文件,然后用VS2017打开查看 异常所在的代码位置。
#include <strsafe.h> //为了调用函数 StringCchPrintf
#include <DbgHelp.h>
//生产DUMP文件
int GenerateMiniDump(HANDLE hFile, PEXCEPTION_POINTERS pExceptionPointers, PWCHAR pwAppName)
{
BOOL bOwnDumpFile = FALSE;
HANDLE hDumpFile = hFile;
MINIDUMP_EXCEPTION_INFORMATION ExpParam;
typedef BOOL(WINAPI * MiniDumpWriteDumpT)(
HANDLE,
DWORD,
HANDLE,
MINIDUMP_TYPE,
PMINIDUMP_EXCEPTION_INFORMATION,
PMINIDUMP_USER_STREAM_INFORMATION,
PMINIDUMP_CALLBACK_INFORMATION
);
MiniDumpWriteDumpT pfnMiniDumpWriteDump = NULL;
HMODULE hDbgHelp = LoadLibrary(L"DbgHelp.dll");
if (hDbgHelp)
pfnMiniDumpWriteDump = (MiniDumpWriteDumpT)GetProcAddress(hDbgHelp, "MiniDumpWriteDump");
if (pfnMiniDumpWriteDump)
{
if (hDumpFile == NULL || hDumpFile == INVALID_HANDLE_VALUE)
{
TCHAR szPath[MAX_PATH] = { 0 };
TCHAR szFileName[MAX_PATH] = { 0 };
TCHAR* szAppName = pwAppName;
TCHAR* szVersion = L"v1.0";
TCHAR dwBufferSize = MAX_PATH;
SYSTEMTIME stLocalTime;
GetLocalTime(&stLocalTime);
GetTempPath(dwBufferSize, szPath);
StringCchPrintf(szFileName, MAX_PATH, L"%s%s", szPath, szAppName);
CreateDirectory(szFileName, NULL);
StringCchPrintf(szFileName, MAX_PATH, L"%s%s\\%s-%04d%02d%02d-%02d%02d%02d-%ld-%ld.dmp",
szPath, szAppName, szVersion,
stLocalTime.wYear, stLocalTime.wMonth, stLocalTime.wDay,
stLocalTime.wHour, stLocalTime.wMinute, stLocalTime.wSecond,
GetCurrentProcessId(), GetCurrentThreadId());
MessageBoxW(NULL, szFileName , L"我的提示", 0);
hDumpFile = CreateFile(szFileName, GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_WRITE | FILE_SHARE_READ, 0, CREATE_ALWAYS, 0, 0);
bOwnDumpFile = TRUE;
OutputDebugString(szFileName);
}
if (hDumpFile != INVALID_HANDLE_VALUE)
{
ExpParam.ThreadId = GetCurrentThreadId();
ExpParam.ExceptionPointers = pExceptionPointers;
ExpParam.ClientPointers = FALSE;
pfnMiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(),
hDumpFile, MiniDumpWithDataSegs, (pExceptionPointers ? &ExpParam : NULL), NULL, NULL);
if (bOwnDumpFile)
CloseHandle(hDumpFile);
}
}
if (hDbgHelp != NULL)
FreeLibrary(hDbgHelp);
return EXCEPTION_EXECUTE_HANDLER;
}
LONG WINAPI ExceptionFilter(LPEXCEPTION_POINTERS lpExceptionInfo)
{
if (IsDebuggerPresent())
{
return EXCEPTION_CONTINUE_SEARCH;
}
return GenerateMiniDump(NULL, lpExceptionInfo, L"myTest"); //自定义文件夹的名称
}
程序入口的地方加入下面的代码
SetUnhandledExceptionFilter(ExceptionFilter);//加入崩溃dump文件功能
最后产生的dum文件在C盘 目录如下:
C:\Users\xxxxx\AppData\Local\Temp\myTest