Windows アプリケーションで Webブラウザーを起動してURLを開く - C#

Windows アプリケーションで Webブラウザを起動してURLを開くコードを紹介します。

概要

WindowsアプリケーションでWebブラウザを起動してURLを開く場合は、System.Diagnostics 名前空間のProcessクラスを用いるか、Windows APIのShellExecute()関数を用います。

プログラム例:System.Diagnostics.Processを利用する場合

WPF アプリケーションを作成します。

UI

下図のUIを作成します。フォームにボタンを一つ配置します。


UIのXAMLコードは下記になります。
<Window x:Class="OpenWebsite.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Content="Button" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="87" Height="24" Click="Button_Click"/>
    </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 OpenWebsite
{
  /// <summary>
  /// MainWindow.xaml の相互作用ロジック
  /// </summary>
  public partial class MainWindow : Window
  {
    public enum ShowCommands : int
    {

    public MainWindow()
    {
      InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
      System.Diagnostics.Process.Start("http://www.ipentec.com");
    }
  }
}

解説

System.Diagnostics名前空間のProcessクラスのStartメソッドを呼び出してプロセスを開始します。引数(実行ファイル)にURLを与えるとデフォルトのWebブラウザで与えられたURLを開きます。

実行結果

上記のプロジェクトを実行します。下図のウィンドウが表示されます。


[Button]をクリックするとWebブラウザが開き、指定したURLのWebページが開かれます。

プログラム例:Windows API の ShellExecuteを利用する場合

WPFアプリケーションを作成します。

UI

下図のUIを作成します。先ほどのUIにボタンを一つ追加します。


UIのXAMLコードは下記になります。
<Window x:Class="OpenWebsite.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Content="Button" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="87" Height="24" Click="Button_Click"/>
        <Button Content="Button" HorizontalAlignment="Left" Margin="102,10,0,0" VerticalAlignment="Top" Width="87" RenderTransformOrigin="0.939,0.553" Height="24"/>

    </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;
using System.Windows.Interop; 
using System.Runtime.InteropServices;

namespace OpenWebsite
{
  /// <summary>
  /// MainWindow.xaml の相互作用ロジック
  /// </summary>
  public partial class MainWindow : Window
  {
    public enum ShowCommands : int
    {
      SW_HIDE = 0,
      SW_SHOWNORMAL = 1,
      SW_NORMAL = 1,
      SW_SHOWMINIMIZED = 2,
      SW_SHOWMAXIMIZED = 3,
      SW_MAXIMIZE = 3,
      SW_SHOWNOACTIVATE = 4,
      SW_SHOW = 5,
      SW_MINIMIZE = 6,
      SW_SHOWMINNOACTIVE = 7,
      SW_SHOWNA = 8,
      SW_RESTORE = 9,
      SW_SHOWDEFAULT = 10,
      SW_FORCEMINIMIZE = 11,
      SW_MAX = 11
    }

    [DllImport("shell32.dll")]
    static extern IntPtr ShellExecute(IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, ShowCommands nShowCmd);


    public MainWindow()
    {
      InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
      System.Diagnostics.Process.Start("http://www.ipentec.com");
    }

    //Process を用いたコードは省略

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
      HwndSource source = HwndSource.FromVisual(this) as HwndSource;
      IntPtr handle = source.Handle;
      ShellExecute(handle, "open", "http://www.ipentec.com/", null, null, ShowCommands.SW_SHOW);

    }
  }
}

解説

DllImportを用いてShellExecute()関数をインポートします。WPFアプリケーションの場合は、ウィンドウハンドルはHandleSource.FromVisual()メソッドで取得します。
ShellExecuteの第三引数(実行ファイル)にURLを与えるとデフォルトのWebブラウザで与えられたURLを開きます。

実行結果

上記のプロジェクトを実行します。下図のウィンドウが表示されます。


ShellExecuteのコードをClickイベントに実装したほうの[Button]をクリックします。Webブラウザが表示され指定したURLが開かれます。

補足:Windows FormsアプリでShellExecute()を呼び出す場合

Windows FormでShellExecuteを呼び出す場合についての補足です。

UI

下図のUIを作成します。フォームにボタンを一つ配置します。

コード

下記のコードを記述します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace OpenWebsiteWindowsForm
{
  public partial class FormMain : Form
  {
    public enum ShowCommands : int
    {
      SW_HIDE = 0,
      SW_SHOWNORMAL = 1,
      SW_NORMAL = 1,
      SW_SHOWMINIMIZED = 2,
      SW_SHOWMAXIMIZED = 3,
      SW_MAXIMIZE = 3,
      SW_SHOWNOACTIVATE = 4,
      SW_SHOW = 5,
      SW_MINIMIZE = 6,
      SW_SHOWMINNOACTIVE = 7,
      SW_SHOWNA = 8,
      SW_RESTORE = 9,
      SW_SHOWDEFAULT = 10,
      SW_FORCEMINIMIZE = 11,
      SW_MAX = 11
    }

    [DllImport("shell32.dll")]
    static extern IntPtr ShellExecute(IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, ShowCommands nShowCmd);

    public FormMain()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      ShellExecute(this.Handle, "open", "http://www.ipentec.com/", null, null, ShowCommands.SW_SHOW);
    }
  }
}

解説

Windows Formの場合はウィンドウハンドルはウィンドウのHandleプロパティで取得できるため、ShellExecuteの第一引数はthis.Handleとします。

実行結果

プロジェクトを実行します。下図のウィンドウが表示されます。


[button]をクリックします。ウェブブラウザが表示され、指定したURLのWebページが開かれます。

著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
掲載日: 2015-01-08
iPentec all rights reserverd.