Can I use window hooks in C# to determine if a window gains or loses focus?
I've written a c# application which automates an instance of IE. I'd like to know when internet explorer gains focus and when it looses focus.
From the SHDocVw.InternetExplorer object I can get it's HWND. From there how can I create a message hook to receive WM_KILLFOCUS and WM_FOCUS events (assuming those are the correct events to be listening for :))?
Thanks everyone!!
UPDATE: I found a way I could use to accomplish the above goal without using hooks (which I haven't quite figured out how to do in c# yet), using the .NET framework in this question.
The problem with this code
AutomationFocusChangedEventHandler focusHandler
= new AutomationFocusChangedEventHandler(OnFocusChanged);
Automation.AddAutomationFocusChangedEventHandler(focusHandler);
is that it is easy for a window to be the foreground window and that event won't fire when that window is switched to because it's waiting for a specific UI Element to be in focus. (To test this you can use a function that uses that code and prints a message everytime a new window is in focus, such as the MSDN sample TrackFocus, and then click on a webbrowser. When most 开发者_运维问答webpages or a blank page is being displayed in the browser the event wont fire until the address bar or some other element is selected.) It could probably work if there was a way to modify so that it could throw the event if either no UI Element is in focus or every time an element lost focus (instead being thrown when it gains focused). Anyone have any ideas on how I could fix the above code to solve my problem?
Update 2: I just came across this (article claims you can only hook to mouse and keyboard from c#) as well which may mean I can't use hooks at all for what I'd like to do.
Detailed instructions on setting up a hook from C# are here: http://support.microsoft.com/kb/318804/en-us?fr=1
精彩评论