I am new to windows programming(I know little bit about c and c++). I am trying to create windows dll which registers windows hook for keyboard.I am using eclipse CDT with MinGW(as I dont want to use Visual Studio) to create dll.I was able to create dll for below program(copied from here), but when I try to load it from another program,it hangs with out any error message.
#include <windows.h>
#include <iostream>
#include <stdio.h>
#include<windef.h>
#ifdef __MINGW32__
# define __in
# define __in_z
# define __in_z_opt
#endif
#define WIN32_LEAN_AND_MEAN
#include <d3d9.h>
HINSTANCE hinst;
HHOOK hhk;
LRESULT CALLBACK wireKeyboardProc(int code,WPARAM wParam,LPARAM lParam) {
FILE * fileLog = fopen("C:\\try.txt", "a+");
fprintf(fileLog,"OK");
CallNextHookEx(hhk,code,wParam,lParam);
fclose(fileLog);
return 0;
}
extern "C" __declspec(dllexport) void install() {
hhk = SetWindowsHookEx(WH_KEYBOARD, wireKeyboardProc, hinst, NULL);
}
extern "C" __declspec(dllexport) void uninstall() {
UnhookWindowsHookEx(hhk);
}
BOOL WINAPI DllMain( __in HINSTANCE hinstDLL,
__in DWORD fdwReason,
__in LPVOID lpvReserved
) {
hinst = hinstDLL;
return TRUE;
}
Is this a problem with MinGW? Any Help is appreciated.Thank you. Below is the test program that loads dll.
#include <iostream>
#include <stdio.h>
#include <windows.h>
#include<windef.h>
#define WIN32_LEAN_AND_MEAN
#include <d3d9.h>
int main()
{
HINSTANCE hinst = LoadLibrary("libTestHook.dll");
if (hinst == NULL)
{
printf("null hinst");
}
开发者_如何学JAVA typedef void (*Install)();
typedef void (*Uninstall)();
Install install = (Install) GetProcAddress(hinst, "install");
Uninstall uninstall = (Uninstall) GetProcAddress(hinst, "uninstall");
install();
int foo;
std::cin >> foo;
uninstall();
return 0;
}
libTestHook.dll is the created dll
Your hook dll seems to be alright (except that you must probably use the return value of CallNextHookEx). However if I use this in a console application it hangs; if I use it in a windows application it is ok. This may be due to the fact that hooking is dependent on a windows message queue.
See also this 'C++ Console app, SetWindowsHookEx, Callback is never called'
I don't think it hangs. What a keyboard hook generally does is process a "main event loop" until the program is closed. In this case, I'd assume that this is exactly what's going on. Your program is running, calling the required routine from the dll, and then the dll is continually processing events.
That being said, windows seems to do something strange with terminals and mingw. More specifically, it doesn't play nice, like it does when using MSVS. Perhaps this might also be the cause of your problems - MinGW compiles things more or less like gcc does, however MSVS's cl puts strange declarations in to open terminals and print to them, etc. etc.
Of course, note that at some point you need to call the install()
and the uninstall()
functions in your code - which I'm assuming you've already done.
精彩评论