// HookDll.cpp : Defines the initialization routines for the DLL.
//

#include "stdafx.h"
#include "HookDll.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

BEGIN_MESSAGE_MAP(CHookDllApp, CWinApp)
	//{{AFX_MSG_MAP(CHookDllApp)
		// NOTE - the ClassWizard will add and remove mapping macros here.
		//    DO NOT EDIT what you see in these blocks of generated code!
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CHookDllApp construction

CHookDllApp::CHookDllApp()
{
}

/////////////////////////////////////////////////////////////////////////////
// The one and only CHookDllApp object

CHookDllApp theApp;

HHOOK hHook;
HWND hWndMain;
DWORD dwMessage;

BOOL APIENTRY DllEntry(HANDLE hModule,	// Handle to DLL module
					 DWORD ul_reason_for_call,	// Reason for calling function
					 LPVOID lpReserved ) // Reserved
{
	switch ( ul_reason_for_call )
	{
	case DLL_PROCESS_ATTACH:
		// A process is loading the DLL.
		break;
	case DLL_THREAD_ATTACH:
		// A process is creating a new thread.
		break;
	case DLL_THREAD_DETACH:
		// A thread exits normally.
		break;
	case DLL_PROCESS_DETACH:
		// A process unloads the DLL.
		break;
	}
	return TRUE;
}

//键盘钩子回调函数
LRESULT CALLBACK HookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
	char szKeyState[256] = {0};
	char szBuffer[256] = {0};
	char szAscii[4] = {0};
	CallNextHookEx(hHook, nCode, wParam, lParam);
	GetKeyboardState((PBYTE)szKeyState);
	szKeyState[VK_SHIFT-1] = GetKeyState((BYTE)VK_SHIFT) & 0x000000ff;
	ToAscii(wParam, (lParam>>16), (PBYTE)szKeyState, (LPWORD) szAscii, 0);
	//MessageBox(NULL, TEXT("开始发送消息"), NULL, MB_OK);
	SendMessage(hWndMain, (UINT)dwMessage, (WPARAM)szAscii, NULL);
	return 0;
}

HHOOK InstallHook(HWND hWnd, UINT Message, HINSTANCE hInstance)
{
	dwMessage = Message;
    hWndMain = hWnd;
	hHook = SetWindowsHookEx(WH_KEYBOARD, (HOOKPROC) HookProc, hInstance, NULL);
    return hHook;
}

int UninstallHook(HHOOK hHook)
{
	return UnhookWindowsHookEx(hHook);
}