【问题标题】:How to open a web page from WPF? [duplicate]如何从 WPF 打开网页? [复制]
【发布时间】:2020-11-01 12:25:42
【问题描述】:

使用 Visual Studio 2019 WPF 应用 尝试使用以前对我有用的代码打开网页,但现在出现错误

我收到一条错误消息说 System.ComponentModel.Win32Exception: '系统找不到指定的文件。'

也想在Chrome中打开页面

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

private void Button_Click_1(object sender, RoutedEventArgs e)
    {

        Process.Start("https://www.google.com");

    }

【问题讨论】:

  • 尝试使用 https 而不是 http

标签: c#


【解决方案1】:

我猜你正在使用 .net 核心。您应该将ProcessStartInfo 传递给Process.Start()。如果您希望默认浏览器打开,您可以调用 cmd 为您完成工作。如果您需要特定的浏览器,您也可以提供该浏览器的进程名称。

对于默认浏览器,您可以执行类似的操作

string url = "https://www.google.com";
Process.Start(new ProcessStartInfo("cmd", $"/c start {url}") { CreateNoWindow = true });

【讨论】:

  • 行得通谢谢 -- 我怎样才能让网页在 Chrome 中打开
  • 这是实际工作的代码。还有一些其他响应,其中使用 url 作为参数调用“Explorer”,当 url 包含查询字符串参数时,该方法有时会失败。
【解决方案2】:

要在 Chrome 中打开 URL,请填充 ProcessStartInfo() 类属性,如下所示:

using System.Diagnostics;
using System.Windows;

namespace WpfApp1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string url = "https://www.google.com";

            ProcessStartInfo startInfo = new ProcessStartInfo();

            // To open url in Chrome, specify startInfo.File = "chrome.exe"
            // To open url in FireFox specify firefox.exe
            // To open url in Microsoft Edge specify msedge.exe
            // To open url in default browser specify explorer.exe

            startInfo.FileName = "chrome.exe";
            startInfo.Arguments = url;
            Process.Start(startInfo);
        }
    }
}

【讨论】:

  • 这依赖于安装在用户机器上的特定浏览器(并且也在路径上)。依赖这些东西是一种不好的做法,而是使用它们作为“默认”浏览器并让它处理 url。
  • Jamal - 我喜欢你的代码,我确实尝试过运行它,但是当它到达 Process.Start 时,它给了我我得到的原始错误 - 我收到一条错误消息,说 System.ComponentModel .Win32Exception: '系统找不到指定的文件。' - 也许我错过了一个参考,但我不知道如何诊断它,你能帮忙吗?谢谢
  • @Bigshop,您能否创建一个新的 WPF 应用程序并看看会发生什么。也许您缺少一些参考资料。我之前评论过这样做,但是一些角色删除了我的 cmets!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-07
  • 2013-08-22
  • 2018-07-23
  • 1970-01-01
  • 2017-04-02
  • 1970-01-01
  • 2012-06-18
相关资源
最近更新 更多