mfc_Key_Hook - 8BitsCoding/RobotMentor GitHub Wiki
ํค ํํน์ด๋?
ํ์ฌ ํ์ฑํ๋ ํ๋ก๊ทธ๋จ (๊ฐ๋ น ๋ฉ๋ชจ์ฅ)์์ ์ ๋ ฅ๋๋ ํค๋ฉ์์ง๋ฅผ ๋นํ์ฑํ๋ ํ๋ก๊ทธ๋จ์์ ๋ฐ์์ค๋ ๊ฒ์ ์๋ฏธ
๊ตฌํ์ ๋ฐฉ๋ฒ์ dll์ ๋ง๋ค์ด ํ ํ๋ก๊ทธ๋จ์์ ๋ฐ์ ํค ๋ฉ์์ง๋ฅผ ๋ค๋ฅธ ํ๋ก๊ทธ๋จ์ผ๋ก ์๋์ฐ ๋ฉ์์ง๋ฅผ ์ก์ ํด์ฃผ๋ ํํ๋ก ๊ตฌํ!!
dll๋ถํฐ ๋ง๋ค์ด๋ณด์.
์ ํ๋ก์ ํธ -> Windows ๋ฐ์คํฌํฑ -> Windows ๋ฐ์คํฌํฑ ๋ง๋ฒ์ฌ
// dllmain.cpp
#include "pch.h"
HINSTANCE gh_instance;
HHOOK gh_next_hook;
HWND gh_target_wnd;
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
gh_instance = hModule;
return TRUE;
}
LRESULT CALLBACK KeyboardProc(int a_code, WPARAM wParam, LPARAM lParam)
{
// ํํน ์ ์ฒ๋ฆฌ ํจ์
if(a_code == HC_ACTION) {
if(gh_target_wnd != NULL) {
::PostMessage(gh_target_wnd, 27001, wParam, lParam);
}
else UninstallKeyHook()
}
return CallNextHookEx(gh_next_hook, a_code, wParam, lParam);
}
extern "C" __declspec(dllexport) void InstallKeyHook()
{
// ํํน ์๋
gh_target_wnd = ::FindWindow(NULL, L"TipsSpy");
gh_next_hook = SetWindowsHookEx(WH_KEYBOARD, KeyboardProc, gh_instance, 0);
}
extern "C" __declspec(dllexport) void UninstallKeyHook()
{
// ํํน ํด์
UnhookWindowsHookEx(gh_next_hook);
}
์ฝ๋์ค๋ช
gh_instance = hModule;
: dll์ด Hookingํ ํ๋ก๊ทธ๋จ์ Attatch๋ ๊ฒฝ์ฐ HINSTANCE๋ฅผ ์ ์ญ์ผ๋ก ์ ์ฅํ๋ค. ์ ์ฅํ ์ด์ ๋ DllMain์ด ๋๋๋ฉดHMODULE hModule
์ ์ฌ๋ผ์ง๊ธฐ ๋๋ฌธ์.
HHOOK gh_next_hook;
: ๋ค์์ผ๋ก ํํนํ ํ๋ก์ธ์ค ์ ์ฅ
HWND gh_target_wnd;
: ํํน ์ ๋ณด๋ฅผ ๋๊ฒจ์ค ์๋์ฐ
SetWindowsHookEx(WH_KEYBOARD, KeyboardProc, gh_instance, 0);
: WH_KEYBOARD ํค๋ณด๋ ๋ฉ์์ง์ ๋ํด์ ํํน์ ํ๊ณ , ํํน ์ KeyboardProcํจ์๋ฅผ ํธ์ถํ๋ค. gh_instance์์ ํํน์งํ
extern "C"
: ๋ฅผ ๋ถ์ด๋ ์ด์ ๋ C์คํ์ผ ์ฝ๋ฉ ํจ์๋ฅผ ๋ฐ๋ก ์ฐพ๊ธฐ์ํจ์ด๋ค.
__declspec(dllexport)
: dll ์ธ๋ถ์์๋ ํธ์ถํด์ ์ฌ์ฉํ ์ ์์์ ์ ์ธ
dll๊น์ง๋ ์์ฑ
ํ๊ฒ ํ๋ก๊ทธ๋จ ์ฝ๋ฉ
dll์ ์ฐ๊ฒฐํด๋ณด์.
// Dlg.h
private:
HINSTANCE mh_hook_dll;
// Dlg.cpp
// OnInitDlg
mh_hook_dll = ::LoadLibraryA("TipsMon.dll");
// void InstallKeyHook()์ ๋ํ Function Pointer
void (*fp)(void) = (void(*)(void))GetProcAddress(mh_hook_dll, "InstallKeyHook");
if(fp != NULL) // ์ ์์ฑ์ด ๋์๋ ํ์ธ
// On27001
CString str;
str.Format(L"%08X %08X", wParam, lParam);
int index = m_event_list.InsertString(-1, str);
m_event_list.SetCurSel(index);
// OnDestroy
void (*fp)(void) = (void(*)(void))GetProcAddress(mh_hook_dll, "UnInstallKeyHook");
if(fp != NULL) // ์ ์์ฑ์ด ๋์๋ ํ์ธ
::FreeLibrary(mh_hook_dll); // Attach๋ dll์ Detach
KeyUp, KeyDown ํ์ธ
// On27001
CString str;
if(lParam & 0x80000000) {
str.Format(L"[Key up] %08X(%c) %08X", wParam, lParam);
// edit box์ ๋ฐ๋ก ๊ทธ๋ ค๋ณธ๋ค.
m_show_edit.PostMessage(WM_KEYUP, wParam, lParam);
}
else {
str.Format(L"[Key down] %08X(%c) %08X", wParam, lParam);
// edit box์ ๋ฐ๋ก ๊ทธ๋ ค๋ณธ๋ค.
m_show_edit.PostMessage(WM_KEYDOWN, wParam, lParam);
}
int index = m_event_list.InsertString(-1, str);
m_event_list.SetCurSel(index);