0

I have a saved url in a database linked to a windows form. How do I take the url and open a web broswer?

this is where its stored

m_dtMedia.Rows[m_rowPosition]["File_Path"]

what I want is when you click a button for the web broswer to oepn up.

Joshua Hornby
  • 283
  • 2
  • 6
  • 18
  • 1
    possible duplicate of [Launch a URL from a WinForms app](http://stackoverflow.com/questions/425381/launch-a-url-from-a-winforms-app) – Ken White May 09 '12 at 22:49

2 Answers2

1
private static void OpenBrowser(string url)
{
        if (url != null)
        {
            Process process = new Process();
            process.StartInfo.FileName = "rundll32.exe";
            process.StartInfo.Arguments = "url.dll,FileProtocolHandler " + url;
            process.StartInfo.UseShellExecute = true;
            process.Start();
        }
}

Since spawning another process takes a bit of time, while that is occuring your UI will be blocked. I recommend calling this method from a background thread. For example:

Task.Factory.StartNew(()=>{OpenBrowser(url);});

This method is used because calling Process.Start(string) from a UI thread causes an exception

Peter Ritchie
  • 35,463
  • 9
  • 80
  • 98
  • 3
    This is waaaay too much code for what the question asks. :) Not downvoting, but `System.Diagnostics.Process.Start("http://www.website.com")` works fine by itself. – Ken White May 09 '12 at 22:48
  • Never seen anyone use url.dll,FileProtocolHandler before. Interesting decision. Why this method? – P.Brian.Mackey May 09 '12 at 22:55
  • Calling Process.Start from the UI thread will block your UI making it unresponsive until the browser opens the site. You cannot call Process.Start(string) from the UI thread--it causes an exception. To open a process from a thread other than the main UI thread you have to go through the above hoops. – Peter Ritchie May 09 '12 at 23:09
  • _"You cannot call Process.Start(string) from the UI thread--it causes an exception."_ - no it doesn't. To verify, I have just tried it and it works without an exception. It will however block the UI as you say, but (on my machine at least) launching a url is so quick it is not noticeable. – adrianbanks May 09 '12 at 23:31
  • It used to throw a System.ComponentModel.Win32Exception; maybe that got fixed in the Framework at some point. – Peter Ritchie May 10 '12 at 00:14
1

You can just start a new process with the url as the target/filename:

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

This will have the effect of using the default browser to load the url.

adrianbanks
  • 81,306
  • 22
  • 176
  • 206