How to get the focus ctrl window of another window?

   I want to get the system-wide current focus ctrl window, no matter which is the child window of my application or not.
    I know I can use the following method to do so:

but, I am wondering whether it will consume much system resources and times or not. Is there any lighter method to achieve the same goal or not?

Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

robpittConnect With a Mentor Commented:
If you need an example of what Madshi is talking about see

The above is a tiny sample I wrote for someone else, but I've adapted to to suit your needs.

It implements a WH_CBT hook dll and then keeps track of the currently active window.

It also (optionally) has a method to call you back whenever the focus changes.


PS Madshi, sorry for posting the same solution as you - but I had this working sample code lying arround. I leave it "whjiang" to figure out how to distribute the points.

I'm not sure about the performance hit of the method you're using. But one thing I can say is this: If you do this check regularly in a loop or something like that, the system will begin to swallow some double clicks. I had this problem when I was doing the same thing (well, I needed the current mouse cursor (GetCursor), so was not 100% the same, but almost) every 500ms or something like that.

An alternative would be to use a system wide hook (SetWindowsHookEx) to get system wide access to the message WM_SETFOCUS (for me it was WM_SETCURSOR). A hook also costs some performance, but at least you won't have that double click problem anymore. This system wide hook solution is the one I'm currently using and it works quite fine.

P.S: Of course the callback function for the system wide hook has to be in a little dll...

Regards, Madshi.
Rob, no problem, after all our main duty is to help, and a code sample surely helps more than only showing the way. I have no problem, if you get the points, when you earned them...   :-)
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

whjiangAuthor Commented:
   I have tried the method you two recommended. But there is still a problem:  if there is no window focus changed since my application started, then no CBT_SETFOCUS message can be recorded. So I can not tell the current focus window unless user change the focus window. From then on everything is ok.

     How can this initialization problem being solved?
Just use your AttachThreadInput code once to initialize the stuff.

Regards, Madshi.
Yep, my code works by tracking changes after the program starts up, hence it doesn't actually know where the focus starts off. Madshi's solution will get arround this limitation.
All Courses

From novice to tech pro — start learning today.