簡單說就是在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()函數中處理最終的異常。安全