using InContext SetWinEventHook
843829Apr 11 2007 — edited Apr 11 2007Hi,
I'm calling SetWinEventHook from Java code. In the C++ wineventProc function I pass back the handle of the window that fired the event into a Java method . For IN_CONTEXT, I'm using GetModuleHandle("DllName.dll"). For OUTOF_CONTEXT , I'm using GetModuleHandle(NULL). Works fine with WINEVENT_OUTOFCONTEXT flag but not with WINEVENT_INCONTEXT.
When I use WINEVENT_INCONTEXT flag, the system hangs while sending the handle(hwnd) back to the java method but it works fine if I don't have to send anything back to Java code. I suspect the problem is that I'm not using AttachcurrentThread() method properly but cannot figure it out. Any idea what's going wrong?
Here is the code:
//Global Variables
static HHOOK hk= 0;
static JavaVM *jvm = NULL;
static jclass jcls = NULL;
VOID CALLBACK fnWinEvent(HWINEVENTHOOK hook, DWORD evnt, HWND hwnd,
LONG idObject, LONG idChild,
DWORD dwEventThread, DWORD dwmsEventTime)
{
IAccessible* pAcc = NULL;
VARIANT varChild;
HRESULT hr = AccessibleObjectFromEvent(hwnd, idObject, idChild, &pAcc, &varChild);
IAccessible* pAcc = NULL;
VARIANT varChild;
HRESULT hr = AccessibleObjectFromEvent(hwnd, idObject, idChild, &pAcc;, &varChild;
if ((hr == S_OK) && (pAcc != NULL))
{
BSTR bstrName;
pAcc->get_accName(varChild, &bstrName;
printf("%S\n", bstrName);
SysFreeString(bstrName);
pAcc->Release();
}
if(jvm!=NULL){
JNIEnv* jenv;
int res = jvm->AttachCurrentThread((void **)&jenv, NULL);
if(res==0 && (jenv!=NULL)){
jmethodID jmeth = jenv->GetStaticMethodID(jcls, "javaCallback", "(II)V");
jenv->CallStaticVoidMethod(jcls, jmeth, hwnd, (int)evnt );
}
jvm->DetachCurrentThread();
}
}
JNIEXPORT jint JNICALL Java_setWinEventHook
(JNIEnv * env, jclass cls, jint emin, jint emax, jint pid, jint tid){
if (jvm == NULL) {
env->GetJavaVM(&jvm);
}
jcls = cls;
HWINEVENTHOOK hook = NULL;
if (hook == NULL) {
//in context - hangs when events are fired by any process other than javaw.exe
//HMODULE modHandle = GetModuleHandle(_T("MyHook.dll"));
//hook = SetWinEventHook(emin, emax, modHandle, (WINEVENTPROC) pid, 0, 0, WINEVENT_INCONTEXT);
//out of context - works fine
HMODULE modHandle = GetModuleHandle(NULL);
hook = SetWinEventHook(emin, emax, modHandle , fnWinEvent,pid, tid, WINEVENT_OUT_OFCONTEXT);
}
return (int)hook;
}
//Java Code:
public final static int setHook(int eventMin, int eventMax, int idProcess, int idThread) {
loadLibrary("MyHook.dll");
int hook = -1;
// only need focus events
hook = setWinEventHook(0x8005, 0x8005, idProcess, idThread);
return hook;
}
protected native static int setWinEventHook (int eventMin, int eventMax, int idThread, int idProcess);
protected static void javaCallback (int hwnd, int eventType)
{
System.out.println("Handle="+hwnd+";event="+ eventType);
}