C#

C# ショートカットを作成する

プログラムを起動するための「ショートカット」は皆さんご存知かと思います。
今回は、この「ショートカット」をプログラムで作成してみます。
C#でショートカットを作成するには、おもに2種類の方法があります。

  • Windows Script Hostで作る
  • リフレクションで作る

 

どちらも、似たようなコードになりますが、ショートカットが1つできるだけ・・・の割にプログラムのコードではいろいろ書けます。

ショートカットに設定される情報は、

必ず必要な情報

  • 作成するショートカットのファイル名
  • 起動するプログラムなどのパス

 

必要であれば設定する情報

  • アイコン
  • 作業フォルダ
  • 起動するプログラムの追加の引数
  • ショートカットキー
  • コメント

これらは、下記の図のようなプロパティで設定されます。

 

WSHでショートカットを作る

WSHでショートカットを作るには、Windows Script Host Object Modelを参照設定に追加します。
参照の追加では”COM”タブにあります。

コードは下記のようになります。設定項目はちょっと多めにしています。

static void Main(string[] args)
{
    // ショートカットそのもののパス
    string shortcutPath = System.IO.Path.Combine(Environment.GetFolderPath(System.Environment.SpecialFolder.DesktopDirectory), @"MyApp.lnk");
    // ショートカットのリンク先(起動するプログラムのパス)
    string targetPath = Application.ExecutablePath;

    // WshShellを作成
    IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell();
    // ショートカットのパスを指定して、WshShortcutを作成
    IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutPath);
    // ①リンク先
    shortcut.TargetPath = targetPath;
    // ②引数
    shortcut.Arguments = "/a /b /c";
    // ③作業フォルダ
    shortcut.WorkingDirectory = Application.StartupPath;
    // ④実行時の大きさ 1が通常、3が最大化、7が最小化
    shortcut.WindowStyle = 1;
    // ⑤コメント
    shortcut.Description = "テストのアプリケーション";
    // ⑥アイコンのパス 自分のEXEファイルのインデックス0のアイコン
    shortcut.IconLocation = Application.ExecutablePath + ",0";

    // ショートカットを作成
    shortcut.Save();

    // 後始末
    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(shortcut);
    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(shell);
}

 

リフレクションでショートカットを作る

リフレクションでWindows Script Host Object Modelを参照設定に追加せず、動的にWshShellを作成してショートカットを作成できます。

static void Main(string[] args)
{
    // ショートカットそのもののパス
    string shortcutPath = System.IO.Path.Combine(Environment.GetFolderPath(System.Environment.SpecialFolder.DesktopDirectory), @"MyApp.lnk");
    // ショートカットのリンク先(起動するプログラムのパス)
    //string targetPath = Application.ExecutablePath;
    string targetPath = Application.StartupPath;

    // WshShellを作成
    Type t = Type.GetTypeFromCLSID(new Guid("72C24DD5-D70A-438B-8A42-98424B88AFB8"));
    dynamic shell = Activator.CreateInstance(t);

    //WshShortcutを作成
    var shortcut = shell.CreateShortcut(shortcutPath);

    //リンク先
    shortcut.TargetPath = targetPath;
    //アイコンのパス
    shortcut.IconLocation = Application.ExecutablePath + ",0";

    // 引数
    //shortcut.Arguments = "/a /b /c";
    // 作業フォルダ
    shortcut.WorkingDirectory = Application.StartupPath;
    // 実行時の大きさ 1が通常、3が最大化、7が最小化
    shortcut.WindowStyle = 1;
    // コメント
    shortcut.Description = "テストのアプリケーション";

    //ショートカットを作成
    shortcut.Save();

    //後始末
    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(shortcut);
    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(shell);
}

 

今回は、デスクトップにショートカットを作成してみましたが、当然ほかのフォルダでも生成させることはできます。

 

タイトルとURLをコピーしました