Automation.AddStructureChangedEventHandler Method (AutomationElement, TreeScope, StructureChangedEventHandler)


Registers the method that will handle structure-changed events.

Namespace:   System.Windows.Automation
Assembly:  UIAutomationClient (in UIAutomationClient.dll)

public static void AddStructureChangedEventHandler(
	AutomationElement element,
	TreeScope scope,
	StructureChangedEventHandler eventHandler


Type: System.Windows.Automation.AutomationElement

The UI Automation element with which to associate the event handler.

Type: System.Windows.Automation.TreeScope

The scope of events to be handled; that is, whether they are on the element itself, or on its ancestors and descendants.

Type: System.Windows.Automation.StructureChangedEventHandler

The method to call when the structure-changed event occurs.

eventHandler can be an instance of the method, or a reference to the method (AddressOf in Visual Basic).

The following example shows a structure-changed event handler delegate that will be called whenever the subtree of the specified AutomationElement changes.

/// <summary>
/// Handles structure-changed events. If a new app window has been added, this method ensures
/// it's in the list of runtime IDs and subscribed to window-close events.
/// </summary>
/// <param name="sender">Object that raised the event.</param>
/// <param name="e">Event arguments.</param>
/// <remarks>
/// An exception can be thrown by the UI Automation core if the element disappears
/// before it can be processed -- for example, if a menu item is only briefly visible. 
/// This exception cannot be caught here because it crosses native/managed boundaries. 
/// In the debugger, you can ignore it and continue execution. The exception does not cause
/// a break when the executable is being run.
/// </remarks>
private void OnStructureChanged(object sender, StructureChangedEventArgs e)
    AutomationElement element = sender as AutomationElement;

    if (e.StructureChangeType == StructureChangeType.ChildAdded)
        Object windowPattern;
        if (false == element.TryGetCurrentPattern(WindowPattern.Pattern, out windowPattern))
        int[] rid = e.GetRuntimeId();
        if (RuntimeIdListed(rid, savedRuntimeIds) < 0)


The following example code adds an instance of the delegate.

// elementRoot is an AutomationElement.
Automation.AddStructureChangedEventHandler(elementRoot, TreeScope.Children, 
    new StructureChangedEventHandler(OnStructureChanged));

.NET Framework
Available since 3.0
Return to top