Is there any event triggered when a new window is

2019-07-21 22:15发布

问题:

I want to know whether there is any event triggered when a new window appears/comes on the desktop. I am open to using COM,WMI,WinApis, UIAutomation or any other method but the language of choice is C#.

The actual requirement: A process has 1 main window and many other windows. The class name of one of the windows is, say, X, (i got this info using pinvoke). Now this window pops up some times whenever there is some notification in the process. I do not want to show this window. I do not have code access to that process so that i can disable that window. So is there any way that i can get an event or any other mechanism which keeps track of the desktop and anytime a window with classname X comes/about to come it hides it.

Do tell if i am not clear with the question. Thanks

EDIT : Simon's answer is really good. I tried that and am able to get notification for all windows except notifications/toast windows such as that of lync's im toast notification or outlook new mail notification. I tried with different elements of Automation Element and Windows Pattern but still could not get those...Any ideas how i can get those...you may read comments in Simon's answer for more context/detail. Once again thanks to Simon for introducing to the great power of UIAUtomation...Loving it!

回答1:

As Damien said in his comment, you can use UI automation, like this in a C# sample console app:

class Program
{
    static void Main(string[] args)
    {
        Automation.AddAutomationEventHandler(WindowPattern.WindowOpenedEvent, AutomationElement.RootElement, TreeScope.Subtree, (sender, e) =>
            {
                AutomationElement src = sender as AutomationElement;
                if (src != null)
                {
                    Console.WriteLine("Class : " + src.Current.ClassName);
                    Console.WriteLine("Title : " + src.Current.Name);
                    Console.WriteLine("Handle: " + src.Current.NativeWindowHandle);
                }
            });

        Console.WriteLine("Press any key to quit...");
        Console.ReadKey(true);
    }
}


回答2:

One option is RegisterShellHookWindow. You supply a window handle that can receive notification messages. The notifications that could be useful to you are HSHELL_WINDOWCREATED or HSHELL_WINDOWACTIVATED.



回答3:

Here MSDN has provided code for registering for windows notifications. But this is specific to Windows Sever 2008. I think similar you can find for your version of Window.