开发者

Win API: How to catch every message from user input?

I want to catch:

  1. Window resize/move/minimize/maximize/close messag开发者_如何学运维es.
  2. Mouseclicks and keyboard presses.
  3. When any program was executed by the user either pressing enter or dblclick. (if possible?)

This should work the same way as the keylock programs works: if you do some event, i can decide via my program will i let Windows handle it, or do i handle it, or both.

How can i do this?


As Hans Passant pointed out, you need the SetWindowsHookEx function.
In the link all possible hooks are explained in detail and the hook functions you need to implement are as well. Here is a small example, how to install a global hook that will process messages, after they are processed by the window.

int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow){

  HHOOK msgHook = SetWindowsHookEx(WH_CALLWNDPROCRET, msgHook, hInstance, 0);

  if(msgHook == NULL){
    //Error handling here
    cout << "Failed to set hook";
  }
  else{
    //Hook has been set and will automatically be removed, when your application exits.
  }

//A clean shutdown should always unhook everything it has installed
UnhookWindowsHookEx(msgHook);

return 0;
}

You can look up the hook functions definition in the MSDN, but it could look like this:

LRESULT CallWndRetProc(int nCode, WPARAM wParam, LPARAM lParam){

  CWPRETSTRUCT* theMessage = (CWPRETSTRUCT*)lParam;

  //now you can read all message parameters and the return value
  //...

  //Always return by calling the next hook in the chain
  return CallNextHookEx(0, nCode, wParam, lParam);
}

The other hooks that you want to install follow the same principle.

See also

  • Hooks Overview
  • Using Hooks
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜