We help IT Professionals succeed at work.

Get window handles of new windows as they are created in VB.NET application.

JServicesLLC asked
NEED:   A way to hook or somehow be notified of any new window handle that is created while my application is running.   I am monitoring for certain windows and would greatly appreciate a way to listen to any new window that is created.   The application is written in VB.NET but I am open to solutions that combine technologies.

Background and Detail:
I have a very simple automation application that is designed to look for certain problem windows or dialog boxes and click a button that the user has predefined.    I have already gotten ALL the information about the target window and target controls (Class Names, Text, etc....) the problem is the way that I am having to monitor for these is to constantly get all the top level windows and then search through all the children etc.    This is a huge waste of valuable system resources.    

I have tried to look up how to create a global hook in VB.NET and have found many things but nothing seems up the ally that I need.    All I need is the window handle (I have the APIs working to get the text and class name etc.. for any handle I feed them, its just the subscribing to the windows messages that is causing me the biggest headache.    to any window created or destroyed.    I plan on creating a collection of these to hold onto for helping me target things but I need a way to do it quickly without having to search every single window and work my way down.
Watch Question

Sinisa VukSoftware architect
Top Expert 2012
You must use SetWindowsHookEx function with HCBT_CREATEWND parameter. Look at MS info:
I suggest to write hook dll in c++ (or similar non .Net language) and use it in .Net.
More articles to study....
Non-English page: http://www.hardforum.ru/t74963/


I appreciate your answer.  The problem is that I am not good at C++ as it's been since college since I have even messed with it.    Does anyone have a VS 2010 buildable project for the hook ?    I thought I found my solution but it will not let me reference it in my project and I am just at a loss at this point.
Global hooks are not supported in the .NET Framework

Except for the WH_KEYBOARD_LL low-level hook and the WH_MOUSE_LL low-level hook, you cannot implement global hooks in the Microsoft .NET Framework. To install a global hook, a hook must have a native DLL export to inject itself in another process that requires a valid, consistent function to call into. This behavior requires a DLL export. The .NET Framework does not support DLL exports. Managed code has no concept of a consistent value for a function pointer because these function pointers are proxies that are built dynamically.
How to set a Windows hook in Visual C# .NET