標籤:
在很多用戶端程式中我們都需要呼叫瀏覽器開啟網頁,這裡分享一個可以在我winform程式呼叫瀏覽器的方法,測試通過了。
下載查看demo
看示範圖
1.調用Google瀏覽器開啟網頁(開啟百度)
2.調用IE開啟頁面(開啟百度)
3.調用使用者預設設定的瀏覽器開啟百度頁面
測試都是通過的,有些電腦因為沒有安裝IE瀏覽器特別是一些Ghost系統,導致IE開啟不成功,這裡我建議大家可以調用Google瀏覽器,因為比較這是現在最主流的瀏覽器之一,Google沒有就開啟系統預設的,實在不行就開啟IE。
項目測試中,還真有一些客戶的電腦用IE打不開,最後安裝Google就可以了。
附加源碼程式demo:
下載查看demo
最後我們加上源碼
/// <summary> /// 調用系統瀏覽器開啟網頁 /// http://m.jb51.net/article/44622.htm /// </summary> /// <param name="url">開啟網頁的連結</param> public static void OpenBrowserUrl(string url) { try { // 64位註冊表路徑 var openKey = @"SOFTWARE\Wow6432Node\Google\Chrome"; if (IntPtr.Size == 4) { // 32位註冊表路徑 openKey = @"SOFTWARE\Google\Chrome"; } RegistryKey appPath = Registry.LocalMachine.OpenSubKey(openKey); // Google瀏覽器就用Google開啟,沒找到就用系統預設的瀏覽器 // Google卸載了,註冊表還沒有清空,程式會返回一個"系統找不到指定的檔案。"的bug var openPath = appPath != null ? "chrome.exe" : "EXPLORER.EXE"; Process.Start(openPath, url); } catch { // 出錯調用使用者預設設定的瀏覽器,還不行就調用IE OpenDefaultBrowserUrl(url); } } /// <summary> /// 用IE開啟瀏覽器 /// </summary> /// <param name="url"></param> public static void OpenIe(string url) { try { Process.Start("iexplore.exe", url); } catch(Exception ex) { LogUtil.WriteException(ex); // IE瀏覽器路徑安裝:C:\Program Files\Internet Explorer // at System.Diagnostics.process.StartWithshellExecuteEx(ProcessStartInfo startInfo)注意這個錯誤 try { if (File.Exists(@"C:\Program Files\Internet Explorer\iexplore.exe")) { ProcessStartInfo processStartInfo = new ProcessStartInfo { FileName = @"C:\Program Files\Internet Explorer\iexplore.exe", Arguments = url, UseShellExecute = false, CreateNoWindow = true }; Process.Start(processStartInfo); } else { if (File.Exists(@"C:\Program Files (x86)\Internet Explorer\iexplore.exe")) { ProcessStartInfo processStartInfo = new ProcessStartInfo { FileName = @"C:\Program Files (x86)\Internet Explorer\iexplore.exe", Arguments = url, UseShellExecute = false, CreateNoWindow = true }; Process.Start(processStartInfo); } else { if (MessageBox.Show("系統未安裝IE瀏覽器,是否下載安裝?", null, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) == DialogResult.Yes) { // 開啟下載連結,從微軟官網下載 OpenBrowserUrl("http://windows.microsoft.com/zh-cn/internet-explorer/download-ie"); } } } } catch (Exception exception) { LogUtil.WriteException(exception); } } } /// <summary> /// 開啟系統預設瀏覽器(使用者自己設定了預設瀏覽器) /// </summary> /// <param name="url"></param> public static void OpenDefaultBrowserUrl(string url) { try { Process.Start("EXPLORER.EXE", url); } catch { OpenIe(url); } }
如果對你有協助希望你可以喜歡,點個贊。
winform呼叫瀏覽器開啟頁面方法分享,希望對大家有協助