When you need to detect and close a specific window, you can do using
AddAutomationEventHandler method in the namespace System.Windows.Automation.
- Set Hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void SetHook() | |
{ | |
System.Windows.Automation.Automation.AddAutomationEventHandler( | |
WindowPattern.WindowOpenedEvent, | |
AutomationElement.RootElement, | |
TreeScope.Children, | |
OnWindowOpened); | |
} |
line 4, set identifier for window open event which want to detect.
line 7, set event handler
line 7, set event handler
- Set Event Handler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static void OnWindowOpened(object sender, AutomationEventArgs e) | |
{ | |
try | |
{ | |
var element = sender as AutomationElement; | |
if (element != null) | |
{ | |
if (element.Current.Name.Equals("WINDOW_TITLE_I_WANT")) | |
{ | |
Console.WriteLine("The winodw is opened."); | |
var Elements_ = element.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Text)); | |
foreach (AutomationElement Element in Elements_) | |
{ | |
Console.WriteLine(Element.Current.Name); | |
} | |
var Elements = element.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button)); | |
foreach(AutomationElement Element in Elements) | |
{ | |
if (Element.Current.Name.Contains("N")) | |
{ | |
var invokePattern = Element.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern; | |
invokePattern?.Invoke(); | |
} | |
} | |
} | |
} | |
} | |
catch(ElementNotAvailableException) | |
{ | |
} | |
} |
line 8, compare name of element with the name to find.
line 15, print the contents of the window
line 22, find the "No" button, it's name has a character "N".
line 24~25, push the button.
Comments
Post a Comment