简单说就是在VS2015中不能直接使用SetUnhandleExceptionFilter()函数,由于安全的考虑,VC++对该函数进行了行为重置,所以要正确使用该函数必须绕过VC++的重置,具体须要增长以下代码:windows
#include <windows.h> #include <tchar.h> #include <stdio.h> LPTOP_LEVEL_EXCEPTION_FILTER WINAPI MyDummySetUnhandledExceptionFilter(LPTOP_LEVEL_EXCEPTION_FILTER lpTopLevelExceptionFilter) { return NULL; } BOOL PreventSetUnhandledExceptionFilter() { HMODULE hKernel32 = LoadLibrary(_T("kernel32.dll")); if (hKernel32 == NULL) return FALSE; void *pOrgEntry = GetProcAddress(hKernel32, "SetUnhandledExceptionFilter"); if (pOrgEntry == NULL) return FALSE; unsigned char newJump[100]; DWORD dwOrgEntryAddr = (DWORD)pOrgEntry; dwOrgEntryAddr += 5; // add 5 for 5 op-codes for jmp far void *pNewFunc = &MyDummySetUnhandledExceptionFilter; DWORD dwNewEntryAddr = (DWORD)pNewFunc; DWORD dwRelativeAddr = dwNewEntryAddr - dwOrgEntryAddr; newJump[0] = 0xE9; // JMP absolute memcpy(&newJump[1], &dwRelativeAddr, sizeof(pNewFunc)); SIZE_T bytesWritten; BOOL bRet = WriteProcessMemory(GetCurrentProcess(), pOrgEntry, newJump, sizeof(pNewFunc) + 1, &bytesWritten); return bRet; } // EXCEPTION_EXECUTE_HANDLER equ 1 表示我已经处理了异常, 能够优雅地结束了 // EXCEPTION_CONTINUE_SEARCH equ 0 表示我不处理, 其余人来吧, 因而windows调用默认的处理程序显示一个错误框, 并结束 // EXCEPTION_CONTINUE_EXECUTION equ - 1 表示错误已经被修复, 请从异常发生处继续执行 LONG WINAPI MyUnhandledExceptionFilter(struct _EXCEPTION_POINTERS *lpTopLevelExceptionFilter) { FatalAppExit(0, _T("OK, You get an Unhandled Exception !")); return EXCEPTION_EXECUTE_HANDLER; } int main() { SetUnhandledExceptionFilter(MyUnhandledExceptionFilter); BOOL bRet = PreventSetUnhandledExceptionFilter(); _tprintf(_T("Prevented: %d"), bRet); // your code }
在MyUnhandledExceptionFilter()函数中处理最终的异常。安全