如何通过UI Automation监控Google Chrome地址栏文本变化
Got it, let's fix this address bar monitoring issue you're dealing with. Since you already have code to locate and read the address bar value, the missing piece is setting up the correct UI Automation event listener—your previous ProgressBar approach didn't work because ProgressBar uses RangeValuePattern, while the address bar relies on ValuePattern for text updates.
Step-by-Step Solution
First, confirm you have a valid reference to the Chrome address bar AutomationElement (your elementx). Then follow these steps:
- Retrieve the ValuePattern from the address bar element
- Register a handler for the
ValuePattern.ValueChangedEvent - Handle the event to capture and report the updated URL
Here's the complete code implementation:
// Assuming you've already located the address bar element as 'elementx' ValuePattern addressBarValuePattern = elementx.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern; // Define the event handler to capture URL changes AutomationEventHandler onAddressBarValueChanged = (sender, e) => { if (sender is AutomationElement updatedAddressBar) { try { ValuePattern pattern = updatedAddressBar.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern; string newUrl = pattern.Current.Value; // Replace this with your reporting logic (e.g., log to file, send to API) Console.WriteLine($"Address bar updated: {newUrl}"); } catch (InvalidOperationException) { // Handle case where the element no longer exists or pattern is unavailable Console.WriteLine("Address bar element is no longer valid."); } } }; // Register the event listener Automation.AddAutomationEventHandler( ValuePattern.ValueChangedEvent, elementx, TreeScope.Element, onAddressBarValueChanged);
Key Notes & Edge Cases to Consider
- Chrome Element Reconstruction: Chrome sometimes recreates the address bar element (e.g., when switching tabs, opening a new window, or after a browser update). You’ll need to re-establish the listener if the original
elementxbecomes invalid. A common workaround is to periodically check if the element exists, or listen for tab/window activation events to re-locate the address bar. - Permission Requirements: If Chrome is running with administrator privileges, your application must also run as admin to successfully monitor the element—otherwise, UI Automation access will be blocked.
- Clean Up the Listener: Don’t forget to remove the event handler when it’s no longer needed to avoid memory leaks:
Automation.RemoveAutomationEventHandler( ValuePattern.ValueChangedEvent, elementx, onAddressBarValueChanged);
Why does accevent.exe detect the changes? Because it’s explicitly listening for ValuePattern.ValueChangedEvent events, which is exactly what we’re using here—your earlier ProgressBar code targeted a different pattern that doesn’t apply to text input controls like the address bar.
内容的提问来源于stack exchange,提问作者Eminem

