如何在WPF中打开默认的Web浏览器

本文关键字:默认 Web 浏览器 WPF | 更新日期: 2023-09-27 17:59:09

我正在尝试创建一个名为WebBrowser的自定义命令,当我点击它时,它将打开我的默认Web浏览器并转到google.com。到目前为止,我只制作了exit命令,我真的很难实现这个命令。任何帮助都将是惊人的。

XAML是:

<Window x:Class="WpfTutorialSamples.Commands.CustomCommandSample"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:self="clr-namespace:WpfTutorialSamples.Commands"
    Title="CustomCommandSample" Height="150" Width="200">
<Window.CommandBindings>
    <CommandBinding Command="self:CustomCommands.Exit" CanExecute="ExitCommand_CanExecute" Executed="ExitCommand_Executed" />
</Window.CommandBindings>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Menu>
        <MenuItem Header="My Command">
            <MenuItem Command="self:CustomCommands.Exit" />               
        </MenuItem>
    </Menu>
    <StackPanel Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
</Window>

背后的代码是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfTutorialSamples.Commands
{
public partial class CustomCommandSample : Window
{
    public CustomCommandSample()
    {
        InitializeComponent();
    }
    private void ExitCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = true;
    }
    private void ExitCommand_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        Application.Current.Shutdown();
    }
  }
  public static class CustomCommands
  {
    public static readonly RoutedUICommand Exit = new RoutedUICommand
            (
                    "Exit",
                    "Exit",
                    typeof(CustomCommands),
                    new InputGestureCollection()
                            {
                                    new KeyGesture(Key.F4, ModifierKeys.Alt)
                            }
            );
  }
  }

我正试图让它看起来像这样:

https://i.stack.imgur.com/k8ezB.png

如何在WPF中打开默认的Web浏览器

您需要一个命令来启动一个新进程,并将URL作为参数提供给它。我在这里使用DelegateCommand,但你可以使用任何自定义的ICommand:

public DelegateCommand StartChromeCommand = new DelegateCommand(OnStartChrome);
private void OnStartChrome()
{
   var process = new Process(new ProcessStartInfo {Arguments = @"http://www.google.com"});
   process.Start();
}