C# または .NET フレームワークを使用してアプリケーション ショートカット (.lnk ファイル) を作成するにはどうすればよいですか?
結果は、指定したアプリケーションまたは URL への .lnk ファイルになります。
思ったほど簡単ではありませんが、vbAcceleratorに ShellLink.csという素晴らしいクラスがあります。
このコードは相互運用機能を使用していますが、WSHに依存していません。
このクラスを使用して、ショートカットを作成するコードは次のとおりです。
private static void configStep_addShortcutToStartupGroup()
{
using (ShellLink shortcut = new ShellLink())
{
shortcut.Target = Application.ExecutablePath;
shortcut.WorkingDirectory = Path.GetDirectoryName(Application.ExecutablePath);
shortcut.Description = "My Shorcut Name Here";
shortcut.DisplayMode = ShellLink.LinkDisplayMode.edmNormal;
shortcut.Save(STARTUP_SHORTCUT_FILEPATH);
}
}
素敵できれい。( .NET 4.0 )
Type t = Type.GetTypeFromCLSID(new Guid("72C24DD5-D70A-438B-8A42-98424B88AFB8")); //Windows Script Host Shell Object
dynamic shell = Activator.CreateInstance(t);
try{
var lnk = shell.CreateShortcut("sc.lnk");
try{
lnk.TargetPath = @"C:\something";
lnk.IconLocation = "shell32.dll, 1";
lnk.Save();
}finally{
Marshal.FinalReleaseComObject(lnk);
}
}finally{
Marshal.FinalReleaseComObject(shell);
}
それだけです。追加のコードは必要ありません。CreateShortcutはファイルからショートカットを読み込むこともできるため、TargetPathなどのプロパティは既存の情報を返します。ショートカット オブジェクトのプロパティ。
動的タイプをサポートしていない .NET のバージョンでも、この方法で可能です。( .NET 3.5 )
Type t = Type.GetTypeFromCLSID(new Guid("72C24DD5-D70A-438B-8A42-98424B88AFB8")); //Windows Script Host Shell Object
object shell = Activator.CreateInstance(t);
try{
object lnk = t.InvokeMember("CreateShortcut", BindingFlags.InvokeMethod, null, shell, new object[]{"sc.lnk"});
try{
t.InvokeMember("TargetPath", BindingFlags.SetProperty, null, lnk, new object[]{@"C:\whatever"});
t.InvokeMember("IconLocation", BindingFlags.SetProperty, null, lnk, new object[]{"shell32.dll, 5"});
t.InvokeMember("Save", BindingFlags.InvokeMethod, null, lnk, null);
}finally{
Marshal.FinalReleaseComObject(lnk);
}
}finally{
Marshal.FinalReleaseComObject(shell);
}
私はこのようなものを見つけました:
private void appShortcutToDesktop(string linkName)
{
string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
using (StreamWriter writer = new StreamWriter(deskDir + "\\" + linkName + ".url"))
{
string app = System.Reflection.Assembly.GetExecutingAssembly().Location;
writer.WriteLine("[InternetShortcut]");
writer.WriteLine("URL=file:///" + app);
writer.WriteLine("IconIndex=0");
string icon = app.Replace('\\', '/');
writer.WriteLine("IconFile=" + icon);
writer.Flush();
}
}
COM ライブラリのインポートも必要ですIWshRuntimeLibrary
。プロジェクトを右クリック -> 参照を追加 -> COM -> IWshRuntimeLibrary -> 追加し、次のコード スニペットを使用します。
private void createShortcutOnDesktop(String executablePath)
{
// Create a new instance of WshShellClass
WshShell lib = new WshShellClass();
// Create the shortcut
IWshRuntimeLibrary.IWshShortcut MyShortcut;
// Choose the path for the shortcut
string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
MyShortcut = (IWshRuntimeLibrary.IWshShortcut)lib.CreateShortcut(@deskDir+"\\AZ.lnk");
// Where the shortcut should point to
//MyShortcut.TargetPath = Application.ExecutablePath;
MyShortcut.TargetPath = @executablePath;
// Description for the shortcut
MyShortcut.Description = "Launch AZ Client";
StreamWriter writer = new StreamWriter(@"D:\AZ\logo.ico");
Properties.Resources.system.Save(writer.BaseStream);
writer.Flush();
writer.Close();
// Location for the shortcut's icon
MyShortcut.IconLocation = @"D:\AZ\logo.ico";
// Create the shortcut at the given path
MyShortcut.Save();
}
SO で見つけたすべての可能性を調査した後、ShellLinkに落ち着きました。
//Create new shortcut
using (var shellShortcut = new ShellShortcut(newShortcutPath)
{
Path = path
WorkingDirectory = workingDir,
Arguments = args,
IconPath = iconPath,
IconIndex = iconIndex,
Description = description,
})
{
shellShortcut.Save();
}
//Read existing shortcut
using (var shellShortcut = new ShellShortcut(existingShortcut))
{
path = shellShortcut.Path;
args = shellShortcut.Arguments;
workingDir = shellShortcut.WorkingDirectory;
...
}
シンプルで効果的であることは別として、著者 (Mattias Sjögren、MS MVP) はある種の COM/PInvoke/Interop の第一人者であり、彼のコードを熟読すると、他の方法よりも堅牢であると思います。
ショートカット ファイルは、いくつかのコマンドライン ユーティリティ (C#/.NET から簡単に呼び出すことができる) でも作成できることに注意してください。私はそれらを試したことはありませんが、NirCmdから始めます(NirSoft には SysInternals のような品質のツールがあります)。
残念ながら、NirCmd はショートカット ファイルを解析できません(作成するだけです) 。出力を csv としてフォーマットすることもできます。lnk-parserも良さそうです (HTML と CSV の両方を出力できます)。
IllidanS4 の回答と同様に、 Windows Script Hostを使用することが、私にとって最も簡単な解決策であることが証明されました (Windows 8 64 ビットでテスト済み)。
ただし、COM タイプをコードから手動でインポートするよりも、COM タイプ ライブラリを参照として追加する方が簡単です。を選択References->Add Reference...
し、「Windows Script Host Object Model」COM->Type Libraries
を見つけて追加します。
IWshRuntimeLibrary
これにより、アクセスできる名前空間がインポートされます。
WshShell shell = new WshShell();
IWshShortcut link = (IWshShortcut)shell.CreateShortcut(LinkPathName);
link.TargetPath=TargetPathName;
link.Save();