いろいろ備忘録日記

主に .NET とか Go とか Flutter とか Python絡みのメモを公開しています。

ショートカットファイルの作成


ショートカットファイルは、.NETのクラスライブラリでは対応していません。
作成するには、以下の方法が一般的な模様。

  • WSHの機能を利用する。
  • IShellLinkのラッパーを作成して利用。


今回は、WSHの機能を利用して作成します。
まず、WSHの機能を参照設定する必要があるのですが
これは、VisualStudioで参照設定を右クリックしてCOMにある

Windows Script Host Object Model ....

というのを選択すればオッケイです。

Interop.IWshRuntimeLibrary.dll

というのが、配置されます。


後は、シェルインスタンスを作成しそこからショートカットを作成します。
以下サンプルです。

using System;
using System.IO;
using System.Reflection;
using IWshRuntimeLibrary;

namespace T{

    public class Test{
    	
    	static void Main(){
    	    
    	    string path = Path.Combile(".", "sample_shortcut.lnk");
    	    
    	    //
    	    // ショートカット作成
    	    //
    	    IWshShell shell = new WshShellClass();
    	    
    	    IWshShortcut shortcut = (IWshShortcut) shell.CreateShortcut(path);
            shortcut.TargetPath   = Assembly.GetEntryAssembly().Location;
            shortcut.Description  = "詳細説明";
            shortcut.Save();

    	}
    }
}

スタートアップにショートカットを作成したりする場合は、
Environment.GetFolderPath(Environment.SpecialFolder.Startup)
で取得したパスでショートカットを作成すれば、起動時に自動起動させる
ことが出来ます。