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?

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


  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)

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



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.

This question has already been answered. Start a new discussion instead.