簡體   English   中英

如何從我的應用程序在用戶默認瀏覽器中啟動URL?

[英]How can I launch a URL in the users default browser from my application?

如何在桌面應用程序中使用一個按鈕,使用戶的默認瀏覽器啟動並顯示應用程序邏輯提供的URL。

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

Process.Start([你的網址])確實是答案,除了非常小眾的情況。 但是,為了完整起見,我會提到我們不久前遇到了這樣一個利基案例:如果你想打開一個“file:\\”url(在我們的例子中,要顯示我們webhelp的本地安裝副本),從shell啟動時,url的參數被拋出。

除非您遇到“正確”解決方案的問題,否則我不推薦使用我們相當苛刻的解決方案,看起來像這樣:

在按鈕的單擊處理程序中:

string browserPath = GetBrowserPath();
if (browserPath == string.Empty)
    browserPath = "iexplore";
Process process = new Process();
process.StartInfo = new ProcessStartInfo(browserPath);
process.StartInfo.Arguments = "\"" + [whatever url you're trying to open] + "\"";
process.Start();

你不應該使用的丑陋功能,除非Process.Start([你的網址])沒有達到預期的效果:

private static string GetBrowserPath()
{
    string browser = string.Empty;
    RegistryKey key = null;

    try
    {
        // try location of default browser path in XP
        key = Registry.ClassesRoot.OpenSubKey(@"HTTP\shell\open\command", false);

        // try location of default browser path in Vista
        if (key == null)
        {
            key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http", false); ;
        }

        if (key != null)
        {
            //trim off quotes
            browser = key.GetValue(null).ToString().ToLower().Replace("\"", "");
            if (!browser.EndsWith("exe"))
            {
                //get rid of everything after the ".exe"
                browser = browser.Substring(0, browser.LastIndexOf(".exe") + 4);
            }

            key.Close();
        }
    }
    catch
    {
        return string.Empty;
    }

    return browser;
}

暫無
暫無

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

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