views:

82

answers:

2

It's tough to write a good title for this one.

I'm working on a WPF application which needs to know about the existence of all other open windows on the system. I'm able to do this by calling the native EnumWindows method just fine, and I can call other native methods to filter out just the windows I'm interested in. This works well.

The problem I'm having is that I want to know when a window is opened or closed (and, ideally, minimized). I can do this by polling with EnumWindows, but I'm finding that to be pretty slow, even if I push it off to another thread.

Is there a better way to get notifications of window opened/closed/minimized? Keep in mind that my knowledge of non-managed code is pretty limited.

A: 

You can use windows hook for this type of thing.

Basically once setup your hook, your callback will be called whenever the messages you're interested get called.

There is a good example on codeproject for setting global system wide hooks with C# code.
Note: There is a unmanaged c++ component to this project, but you don't need to work with it directly.

Brian R. Bondy
Thanks, I'll dig into that. I can at least get the sample running. It looks like it only supports mouse/keyboard events out of the box, and it's unclear whether I can extend it to get the messages I need. Will look further...
Josh Santangelo
Looks like this is a no-go. Only mouse and keyboard hooks are implemented in the library, and extending it requires digging into the C++. Even if I were brave enough to do that, I can't get the project to run from source. Something about the managed call SetUserHookCallback not matching the native signature, but I can't even find any documentation on that method.
Josh Santangelo
@Josh Santangelo: Yes running the demo doesn't require you to go into the C++ but to do what you want to do you would have to. You would use that project as a starting point. It's not trivial but very doable.
Brian R. Bondy
I skipped that demo, but made some progress. Still can't do a global hook, though: http://pastebin.com/1q3qj5iY
Josh Santangelo
A: 

WM_WINDOWPOSCHANGING Message

http://msdn.microsoft.com/en-us/library/ms632653%28VS.85%29.aspx

eschneider
I am using that to get all the windows at application startup, but it is too slow to use to catch changes in the window list at runtime.
Josh Santangelo
How about WM_WINDOWPOSCHANGING Message?
eschneider
I'm able to get window messages from the current process, but not from the OS as a whole. Example here: http://pastebin.com/1q3qj5iY
Josh Santangelo