【C#】【Form】ブラウザから自作Windowsアプリを起動するには

■ はじめに

https://blogs.yahoo.co.jp/dk521123/13069605.html
の続き。
今回は、「【2】ブラウザから自作Windowsアプリを起動するには」を行う。

■ ブラウザから自作Windowsアプリを起動するには

 * 「カスタム URL スキーム」と「クライアント側へのレジストリ登録」で実装する
  => という訳で、クライアント側にレジストリ登録を行う必要がある
                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 ※ 他にもActiveXを使用した実装もあるらしいが、利用せず。
    詳細は、以下「補足:ActiveX での実装について」を参照のこと。

手順

[1] 「カスタム URL スキーム」を使うための登録用のレジストリを作成する(以下「helloworld.reg」)

[2] [1]のファイルをダブルクリックし、Windows 上で「カスタム URL スキーム」を登録する
 => レジストリエディタ「regedit」で、[HKEY_CLASSES_ROOT]配下に[helloworld]が確認できるはず

[3] テスト用HTML(以下「index.html」)および自作Windowsアプリ(以下「Program.cs」「Form1.cs」)を用意する

[4] テスト用HTMLをブラウザで起動し、リンクをクリックする
 => 自作Windowsアプリが起動し、『[helloworld://hello?id=1]』が表示されるはず
後片付け
 * 以下の「unregist.reg」をダブルクリックし、登録したレジストリを削除
 => レジストリエディタ「regedit」で、[HKEY_CLASSES_ROOT]配下に[helloworld]がなくなってるはず

補足:ActiveX での実装について

 * ActiveX は、IEでは対応されているが、Edgeなどのブラウザでは非対応になっている。
http://www.itmedia.co.jp/news/articles/1505/14/news069.html
より抜粋
~~~~~~
 1996年に発表したインターネット関連技術「ActiveX」をはじめ、
「VMLVector Markup Language)」「BHO(Browser Helper Objects)」「VBScript」などの
古い技術は脆弱性の原因になるため、サポートしない。
~~~~~~
そもそも ActiveX とは?
http://www.atmarkit.co.jp/ait/articles/0801/17/news131.html
より抜粋
~~~~~~
Microsoft社が開発したプログラミング技術群の総称
~~~~~~

# 詳しくは、上記のサイトを参照。

■ サンプル

レジストリ

【登録用】helloworld.reg (UTF-8で保存)
Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\helloworld]
@="URL:helloworld Protocol"
"URL Protocol"=""

[HKEY_CLASSES_ROOT\helloworld\shell]

[HKEY_CLASSES_ROOT\helloworld\shell\Open]

[HKEY_CLASSES_ROOT\helloworld\shell\Open\command]
@="\"C:\\SampleForm.exe\" \"%1\""
【削除用】unregist.reg (UTF-8で保存)
Windows Registry Editor Version 5.00
 
[-HKEY_CLASSES_ROOT\helloworld]

テスト用HTML

index.html
<html>
<body>
<a href="helloworld://hello?id=1">Click Me!</a>
</body>
</html>

自作Windowsアプリ

Program.cs
using System;
using System.Windows.Forms;

namespace SampleForm
{
  static class Program
  {
    /// <summary>
    /// アプリケーションのメイン エントリ ポイントです。
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
      Application.Run(new Form1(args));
    }
  }
}
Form1.cs
using System;
using System.Windows.Forms;

namespace SampleForm
{
  public partial class Form1 : Form
  {
    private string value1 = string.Empty;

    public Form1(string[] args)
    {
      InitializeComponent();

      if (args == null || args.Length == 0)
      {
        this.value1 = "引数ゼロ";
      }
      else
      {
        this.value1 = "[" + args[0] + "]";
      }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
      this.label1.Text = this.value1;
    }
  }
}


関連記事

Windows Form ~ 目次 ~

https://blogs.yahoo.co.jp/dk521123/8054245.html

自作Windowsアプリからブラウザを起動するには

https://blogs.yahoo.co.jp/dk521123/13069605.html