so, I have a program that uses a keyboard hook, but starts it in another thread so that it can continue executing. The problem is, the only way I have to stop the mouse hook right now is to just kill the thread using TerminateThread(). However, this does not enable the thread to call the UnhookWindowsHookEx() function for cleanup (which results in glitching every program that uses that mouse hooking).

How can I send a message to this thread that enables it to safely clean itself up (using UnhookWindowsHookEx()), before ending the thread?

Recommended Answers

All 2 Replies

i) create an event and check that event in the child thread

ii) signal the event from main thread when you want to exit

iii) call UnhookWindowEx() and release resouces in the child thread.

psudo code

LONG WINAPI ThreadFunc(LPVOID arg)
{

  HANDLE hEvent = OpenEvent(...,"ChildEvent");
  
  // Perform Coding.

  // here you can check whether the event is signalled or not.
   WaitForSingleObject(hEvent, INFINITE); 

}

int main ()
{
 // .. Something like below
  HANLDE hEvent = CreateEvent(...);
  HANDLE hThread = _beginthreadex(...., ThreadFunc);

 // perform the coding of main thread.

  // Signal the Event, if the child thread is still running.
  GetExitCodeThread(hThread, &dwExitCode);
  if (dwExitCode == STILL_ACTIVE)
      SetEvent(hEvent);

  // still for the safe side
  WaitForSingleObject(hThread, INFINITE);   

  CloseHandle(hThread);
  CloseHandle(hEvent);

}

Well in the ThreadFunc I've called the WaitForSingleObject(..., INFINITE) you must know how to change it to wait for the specified Time, if you are not willing to wait synchronously (INFINITE LY).

Another Way is use the SendMessage Or PostMessage API.

thanks.. that was very helpful.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.