You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# WinForms无法获取新版Microsoft Edge(83.0)URL问题求助

解决新版Chromium Edge的URL捕获问题

我完全理解你的困扰——新版基于Chromium的Microsoft Edge(83.0及以上版本)彻底重构了UI控件的自动化结构,你之前依赖的addressEditBox这个AutomationId已经不再使用,所以旧代码无法定位到地址栏控件。下面是适配新版Edge的解决方案:

核心思路

通过Windows系统自带的UI自动化工具(比如Inspect.exe)分析新版Edge的控件结构后,我们需要定位到AutomationId为omniboxInput的Edit控件,这是新版Edge地址栏对应的自动化元素。

修正后的代码

首先确保你的项目引用了UIAutomationClient和UIAutomationTypes两个程序集,然后添加以下代码:

using System;
using System.Diagnostics;
using System.Windows.Automation;

public static class EdgeUrlHelper
{
    public static string GetEdgeUrl(Process process)
    {
        if (process == null)
            throw new ArgumentNullException(nameof(process));
        if (process.MainWindowHandle == IntPtr.Zero)
            return null;

        try
        {
            AutomationElement mainWindow = AutomationElement.FromHandle(process.MainWindowHandle);
            if (mainWindow == null)
                return null;

            // 定位新版Edge的地址栏控件:AutomationId为omniboxInput的Edit控件
            var addressBarCondition = new AndCondition(
                new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit),
                new PropertyCondition(AutomationElement.AutomationIdProperty, "omniboxInput")
            );

            AutomationElement addressBar = mainWindow.FindFirst(TreeScope.Descendants, addressBarCondition);
            if (addressBar == null)
                return null;

            // 获取地址栏的文本内容,移除末尾多余的回车符
            TextPattern textPattern = addressBar.GetCurrentPattern(TextPattern.Pattern) as TextPattern;
            return textPattern?.DocumentRange.GetText(int.MaxValue).TrimEnd('\r');
        }
        catch (Exception ex)
        {
            // 可根据需求添加日志记录,这里直接返回null避免程序崩溃
            // Console.WriteLine($"获取Edge URL失败: {ex.Message}");
            return null;
        }
    }
}

关键说明

  1. 控件定位逻辑变更:新版Edge的地址栏AutomationId从旧版的addressEditBox改为omniboxInput,这是核心差异点。
  2. 搜索范围调整:地址栏属于主窗口的深层子元素,因此需要用TreeScope.Descendants而非TreeScope.Children来遍历搜索。
  3. 异常处理优化:原代码直接抛出异常,这里改为捕获异常后返回null,更符合实际应用的容错需求。
  4. 文本处理:GetText方法返回的文本末尾会带一个回车符,调用TrimEnd('\r')可以得到纯净的URL内容。

使用示例

// 遍历所有正在运行的Edge进程,获取每个窗口的URL
foreach (Process edgeProcess in Process.GetProcessesByName("msedge"))
{
    string url = EdgeUrlHelper.GetEdgeUrl(edgeProcess);
    if (!string.IsNullOrEmpty(url))
    {
        Console.WriteLine($"Edge窗口URL: {url}");
    }
}

内容的提问来源于stack exchange,提问作者Tony Walter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 07:37:43