窗体与Hook

状态: 进行中

/*
HOOK:
	1.進程内Hook
	2.全局Hook
Windows消息機制:
*/

#include <windows.h>

//CUI -> maink 控制台程序
//GUI -> WinMain 圖形界面程序
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd);

//HWND 窗體句柄
//UINT 消息類型,鼠標移動消息,案件消息
//WPARAM 
LRESULT CALLBACK WindowsProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam);

LRESULT CALLBACK HookProc(int nCode,  WPARAM wParam, LPARAM lParam);

HHOOK hookHwnd;

//HINSTANCE:指針類型 應用程式實例句柄
//HINSTANCE:已被廢棄
//LPSTR:char* 字符串指針 命令行參數
//nShowCmd 窗口的顯示方式

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
	//1.設計窗口 Spy++ 窗口類
	TCHAR AppClassName[] = TEXT("NewWindow");//TEXT包裹自適應字符集
	WNDCLASS WindowClass = {0};
	WindowClass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); //加載窗體句柄
	WindowClass.hCursor = LoadCursor(NULL, IDC_ARROW); //加載光標
	WindowClass.hInstance = hInstance; //當前窗體句柄
	WindowClass.lpfnWndProc = (WNDPROC)WindowsProc; //窗體處理函數
	WindowClass.lpszClassName = AppClassName; //窗體類型名
	WindowClass.style = CS_HREDRAW|CS_VREDRAW; //窗體類的風格

	//2.注冊窗口類
	RegisterClass(&WindowClass);

	//3.創建窗口
	HWND hWND = CreateWindow(AppClassName, TEXT("窗體標題"), WS_BORDER| WS_CAPTION| WS_MAXIMIZEBOX| WS_MINIMIZEBOX| WS_SYSMENU,200,100,700,500,NULL,NULL,hInstance,NULL);

	//4.顯示和更新窗口
	ShowWindow(hWND,SW_SHOW);
	UpdateWindow(hWND);

	//5.消息循環 與Hook强關聯
	MSG msg;
	while (GetMessage(&msg, NULL, 0, 0)) //要检索其消息的窗口的句柄。窗口必须属于当前线程
	{
		//將虛擬鍵消息轉換爲字符消息
		TranslateMessage(&msg);
		//將消息分發給窗口處理函數
		DispatchMessage(&msg);
	}

	return 0;
}

LRESULT CALLBACK WindowsProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {

	switch (uMsg)
	{
	case WM_CREATE:
		hookHwnd = SetWindowsHookEx(WH_MOUSE, HookProc, NULL,GetCurrentThreadId()); //安裝Hook的時候返回值為Hook句柄
		break;

	case WM_LBUTTONDOWN:
	{
		int x = LOWORD(lParam);
		int y = HIWORD(lParam);
		wchar_t str[100];
		wsprintf(str, L"鼠標坐標(%d,%d)", x, y);
		MessageBox(hWnd, (LPCWSTR)str, TEXT("Info"), NULL);
		break; 
	}
	case WM_CLOSE:
		DestroyWindow(hWnd);
		break;
	case WM_DESTROY:
		PostQuitMessage(0); //GetMessage処返回0,即退出程式
		break;
	}
	return DefWindowProc(hWnd, uMsg,wParam,lParam);
}

LRESULT CALLBACK HookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
	return CallNextHookEx(hookHwnd, nCode, wParam, lParam); //將code返回給程序
	//return 1; //返回非0,表示已經處理,不會往下傳遞
}
comments powered by Disqus