#include <Windows.h>
#include <iostream>
#include <thread>
#include "detours.h"
HWND hwnd;
static LRESULT(WINAPI* OldSendMessage)(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) = SendMessage;
LRESULT WINAPI NewSendMessage(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) {
MessageBox(hwnd, TEXT("就不关闭!"), TEXT("关闭程序"), MB_OK | MB_ICONINFORMATION);
return 0;
}
void Hook() {
DetourRestoreAfterWith();
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(&(PVOID&)OldSendMessage, NewSendMessage);
DetourTransactionCommit();
}
void UnHook() {
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourDetach(&(PVOID&)OldSendMessage, NewSendMessage);
DetourTransactionCommit();
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
switch (message) {
case WM_CLOSE:
DestroyWindow(hwnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, message, wParam, lParam);
}
return 0;
}
int main(void) {
Hook();
static TCHAR szAppName[] = TEXT("TextWindow");
MSG msg;
WNDCLASS wndclass;
wndclass.style = CS_HREDRAW | CS_VREDRAW;
wndclass.lpszClassName = szAppName;
wndclass.lpszMenuName = NULL;
wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wndclass.lpfnWndProc = WndProc;
wndclass.cbWndExtra = 0;
wndclass.cbClsExtra = 0;
wndclass.hInstance = GetModuleHandle(0);
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
UnregisterClass(wndclass.lpszClassName, GetModuleHandle(0));
if (!RegisterClass(&wndclass)) {
MessageBox(NULL, TEXT("窗口注册失败"), TEXT("错误"), MB_OK | MB_ICONERROR);
return 0;
}
hwnd = CreateWindow(szAppName, TEXT("测试窗口"), WS_OVERLAPPEDWINDOW,
0, 0, 500, 400, NULL, NULL, GetModuleHandle(0), NULL);
ShowWindow(hwnd, SW_SHOW);
UpdateWindow(hwnd);
std::thread close_work = std::thread([&]() {
for (int i = 0; i < 5; ++i) {
std::cout << "close work: " << 5 - i << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
::SendMessage(hwnd, WM_CLOSE, 0, 0);
});
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
if (close_work.joinable()) {
close_work.join();
}
std::cout << "Finish" << std::endl;
UnHook();
getchar();
return 0;
}