OzBob
OzBob

Reputation: 4520

Open Browser with URL WPF

How to open an external browser by hyperlink, in a browser it would be target='_top'.

What is the code in a WPF netcore 3.1 app?

  1. Use CommandParameter

    <TextBlock>
        <Hyperlink CommandParameter="{Binding ExternalURL}"
                   Command="{Binding NavHomeViewCommand}" >Open in Browser ...
        </Hyperlink>
    </TextBlock>
    
  2. Change DelegateCommand to use object parameter (using the prismlibrary mvvm pattern)

    navHomeViewCommand = new DelegateCommand<object>(NavHomeView);
    
  3. Command Properties:

    public string ExternalURL{ get => "https://www.google.com/";}
    private readonly ICommand navHomeViewCommand;
    public ICommand NavHomeViewCommand
    {
        get { return navHomeViewCommand; }
    }
    
  4. Open a browser

    private void NavHomeView(object ID)
    {
        if(obj is string destinationurl)
            System.Diagnostics.Process.Start("https://google.com");  //???????   
    }
    

An exception is thrown 'unknown executable'.

Upvotes: 4

Views: 7363

Answers (2)

OzBob
OzBob

Reputation: 4520

Solution that opens Windows OS level default Browser with the specified URL. Recommended via WPF Github issue 2566:

        var destinationurl = "https://www.bing.com/";
        var sInfo = new System.Diagnostics.ProcessStartInfo(destinationurl)
        {
            UseShellExecute = true,
        };
        System.Diagnostics.Process.Start(sInfo);

OLD: The solution that opens a silent CMD prompt and opens the Windows OS default browser:

    private void NavHomeView(object ID)
    {
        //return;
        if (IDis string destinationurl)
        {
            var link = new Uri(destinationurl);
            var psi = new ProcessStartInfo
            {
                FileName = "cmd",
                WindowStyle = ProcessWindowStyle.Hidden,
                UseShellExecute = false,
                CreateNoWindow = true,
                Arguments = $"/c start {link.AbsoluteUri}"
            };
            Process.Start(psi);
        ...

but if your intent is to package the app using the MSIX packaging project type and put it in the Windows Store, then you'll fail certification for using CMD.EXE.

Upvotes: 9

DevStranding
DevStranding

Reputation: 51

System.Diagnostics.Process.Start(@"C:\Program Files (x86)\Google\Chrome\Application\Chrome.exe", "https://www.google.fr");

or if you don't know path of file .exe of navigator

var UrlExterne = "https://www.google.fr";
var filetemp = $"{Path.GetTempFileName()}.url";
try
{
     using (var sw = new StreamWriter(filetemp))
     {
          sw.WriteLine("[InternetShortcut]");
          sw.WriteLine($"URL={UrlExterne}");
          sw.Close();
      }
      System.Diagnostics.Process.Start(filetemp);
 }
 finally
 {
     if(File.Exists(filetemp))
          File.Delete(filetemp);
 }

Upvotes: 0

Related Questions