簡體   English   中英

如何在 C# 的默認瀏覽器中打開

[英]How to open in default browser in C#

我正在設計一個小型 C# 應用程序,其中有一個 web 瀏覽器。 我目前在我的計算機上有我所有的默認設置,說谷歌瀏覽器是我的默認瀏覽器,但是當我單擊我的應用程序中的鏈接以在新的 window 中打開時,它會打開 Internet Explorer。 有沒有辦法讓這些鏈接在默認瀏覽器中打開? 還是我的電腦有問題?

我的問題是我在應用程序中有一個網絡瀏覽器,所以說你 go 到谷歌並輸入“堆棧溢出”並右鍵單擊第一個鏈接並單擊“在新窗口中打開”它在 IE 而不是 Chrome 中打開。 這是我編碼不正確,還是我的計算機上的設置不正確

===編輯===

這真的很煩人。 我已經知道瀏覽器是 IE,但我之前運行良好。 當我單擊一個鏈接時,它會在 chrome 中打開。 我當時正在使用sharp development制作應用程序,因為我無法啟動c# express。 我做了一個新的 windows 安裝,由於我的應用程序並沒有走得太遠,我決定重新開始,現在我遇到了這個問題。 這就是為什么我不確定它是否是我的電腦。 為什么點擊鏈接時 IE 會啟動整個瀏覽器,而不是簡單地在默認瀏覽器中打開新鏈接?

你可以寫

System.Diagnostics.Process.Start("http://google.com");

編輯WebBrowser控件是 IE 的嵌入式副本。
因此,其中的任何鏈接都將在 IE 中打開。

要更改此行為,您可以處理Navigating事件。

對於那些在 dotnet core 中發現這個問題的人。 我在這里找到了解決方案

代碼:

private void OpenUrl(string url)
{
    try
    {
        Process.Start(url);
    }
    catch
    {
        // hack because of this: https://github.com/dotnet/corefx/issues/10361
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            url = url.Replace("&", "^&");
            Process.Start(new ProcessStartInfo("cmd", $"/c start {url}") { CreateNoWindow = true });
        }
        else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
        {
            Process.Start("xdg-open", url);
        }
        else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
        {
            Process.Start("open", url);
        }
        else
        {
            throw;
        }
    }
}
public static void GoToSite(string url)
{
     System.Diagnostics.Process.Start(url);
}

這應該可以解決你的問題

您是否嘗試過此處提到的Processhttp : //msdn.microsoft.com/de-de/library/system.diagnostics.process.aspx

你可以用

Process myProcess = new Process();

try
{
    // true is the default, but it is important not to set it to false
    myProcess.StartInfo.UseShellExecute = true; 
    myProcess.StartInfo.FileName = "http://some.domain.tld/bla";
    myProcess.Start();
}
catch (Exception e)
{
    Console.WriteLine(e.Message);
}

經過大量研究,我覺得大多數給定的答案不適用於 dotnet core。 1. System.Diagnostics.Process.Start("http://google.com") ; -- 不適用於 dotnet 核心

2.它會工作,但如果默認瀏覽器是chrome,它會阻止新窗口打開

 myProcess.StartInfo.UseShellExecute = true; 
    myProcess.StartInfo.FileName = "http://some.domain.tld/bla";
    myProcess.Start();

下面是最簡單的,適用於所有場景。

Process.Start("explorer", url);

我的默認瀏覽器是谷歌瀏覽器,接受的答案出現以下錯誤:

系統找不到指定的文件。

我解決了這個問題,並使用以下代碼設法用默認瀏覽器打開了一個 URL:

System.Diagnostics.Process.Start("explorer.exe", "http://google.com");

試試這個,老派的方式;)

public static void openit(string x)
    {
        System.Diagnostics.Process.Start("cmd", "/C start" + " " + x);
    }

使用:openit("www.google.com");

看看GeckoFX 控件

GeckoFX 是一個開源組件,可以輕松地將 Mozilla Gecko (Firefox) 嵌入到任何 .NET Windows 窗體應用程序中。 GeckoFX 用干凈、完整注釋的 C# 編寫,是默認的基於 Internet Explorer 的 WebBrowser 控件的完美替代品。

我在 .NET 5、Windows 和 Windows 窗體中使用它。 它甚至適用於其他默認瀏覽器(例如 Firefox):

Process.Start(new ProcessStartInfo { FileName = url, UseShellExecute = true });

基於這個這個

如果我們使用Process.Start(URL) dotnet core會拋出錯誤。 以下代碼將在dotnet core工作。 您可以添加任何瀏覽器而不是Chrome

var processes = Process.GetProcessesByName("Chrome");
var path  = processes.FirstOrDefault()?.MainModule?.FileName;
Process.Start(path,  url);

這為我打開了默認設置:

System.Diagnostics.Process.Start(e.LinkText.ToString());

我是不是唯一一個不敢在剛剛從互聯網上讀取的字符串上調用System.Diagnostics.Process.Start()的人?

        public bool OnBeforeBrowse(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool userGesture, bool isRedirect)
        {
            Request = request;
            string url = Request.Url;
            
            if (Request.TransitionType != TransitionType.LinkClicked)
            {   // We are only changing the behavoir when someone clicks on a link.
                // Let the embedded browser handle this request itself.
                return false;
            }
            else
            {   // The user clicked on a link.  Something like a filter icon, which links to the help for that filter.
                // We open a new window for that request.  This window cannot change.  It is running a JavaScript
                // application that is talking with the C# main program.
                Uri uri = new Uri(url);
                try
                {
                    switch (uri.Scheme)
                    {
                        case "http":
                        case "https":
                            {   // Stack overflow says that this next line is *the* way to open a URL in the
                                // default browser.  I don't trust it.  Seems like a potential security
                                // flaw to read a string from the network then run it from the shell.  This
                                // way I'm at least verifying that it is an http request and will start a
                                // browser.  The Uri object will also verify and sanitize the URL.
                                System.Diagnostics.Process.Start(uri.ToString());
                                break;
                            }
                        case "showdevtools":
                            {
                                WebBrowser.ShowDevTools();
                                break;
                            }
                    }
                }
                catch { }
                // Tell the browser to cancel the navigation.
                return true;
            }
        }

此代碼旨在與 CefSharp 一起使用,但應該很容易適應。

在 UWP 中:

await Launcher.LaunchUriAsync(new Uri("http://google.com"));

我試過了

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

這適用於大多數情況,但我遇到了一個指向文件的 url 的問題:

系統找不到指定的文件。

所以,我嘗試了這個解決方案,它做了一些修改:

System.Diagnostics.Process.Start("explorer.exe", $"\"{uri}\"");

不使用""包裝 url,資源管理器會打開您的文檔文件夾。

動態打開

string addres= "Print/" + Id + ".htm";
           System.Diagnostics.Process.Start(Path.Combine(Environment.CurrentDirectory, addres));

使用當前版本的資源管理器更新注冊表
@"Software\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION"

public enum BrowserEmulationVersion
{
    Default = 0,
    Version7 = 7000,
    Version8 = 8000,
    Version8Standards = 8888,
    Version9 = 9000,
    Version9Standards = 9999,
    Version10 = 10000,
    Version10Standards = 10001,
    Version11 = 11000,
    Version11Edge = 11001
}

key.SetValue(programName, (int)browserEmulationVersion, RegistryValueKind.DWord);

這適用於 .NET 5 (Windows):

 ProcessStartInfo psi = new ProcessStartInfo {
   FileName = "cmd.exe",
     Arguments = $ "/C start https://stackoverflow.com/",
     WindowStyle = ProcessWindowStyle.Hidden,
     CreateNoWindow = true
 };
 Process.Start(psi);

為了解決 Net 6 的問題,我使用了ChromeLauncher 中的這段代碼,默認瀏覽器就是這樣

internal static class ChromeLauncher
{
    private const string ChromeAppKey = @"\Software\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe";

    private static string ChromeAppFileName
    {
        get
        {
            return (string) (Registry.GetValue("HKEY_LOCAL_MACHINE" + ChromeAppKey, "", null) ??
                                Registry.GetValue("HKEY_CURRENT_USER" + ChromeAppKey, "", null));
        }
    }

    public static void OpenLink(string url)
    {
        string chromeAppFileName = ChromeAppFileName;
        if (string.IsNullOrEmpty(chromeAppFileName))
        {
            throw new Exception("Could not find chrome.exe!");
        }
        Process.Start(chromeAppFileName, url);
    }
}

我會對上述答案之一發表評論,但我還沒有代表。

System.Diagnostics.Process.Start("explorer", "stackoverflow.com");

幾乎可以工作,除非 url 有一個查詢字符串,在這種情況下,此代碼只會打開一個文件資源管理器窗口。 關鍵似乎是 UseShellExecute 標志,如上面 Alex Vang 的回答中所給出的(模其他關於在網絡瀏覽器中啟動隨機字符串的評論)。

您可以使用 cmd 命令start <link>在默認瀏覽器中打開鏈接,此方法適用於具有在 cmd.exe 上執行系統命令的功能的每種語言。

這是我用於.NET 6執行系統命令並重定向輸出和輸入的方法,也很確定它可以在.NET 5上進行一些修改。

using System.Diagnostics.Process cmd = new();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();


cmd.StandardInput.WriteLine("start https://google.com"); 
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
cmd.WaitForExit();

您可以使用此代碼

System.Diagnostics.Process.Start("www.bing.com")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM