Made By 于子軒,2025.2.2
不管是使用System.IO命名空間下的File類來創建快捷方式文件,或是使用Windows Script Host對象創建快捷方式,亦或是使用Shell32對象創建快捷方式,都對用戶很不友好,今天小編為大家帶來一種全新的方式:調用控制面板項(.Cpl)實現“新建快捷方式對話框”
別人的方法:
在C#中,可以使用WshShell對象來創建快捷方式。下面是一個簡單的示例代碼:
csharp復制插入
using IWshRuntimeLibrary;public void CreateShortcut(string targetPath, string shortcutPath)
{WshShell shell = new WshShell();IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);shortcut.TargetPath = targetPath;shortcut.Save();
}
在這個示例中,targetPath
參數指定了目標文件或文件夾的路徑,shortcutPath
參數指定了要創建的快捷方式的路徑。首先,我們創建一個WshShell
對象,然后使用其CreateShortcut
方法創建一個快捷方式對象。接下來,我們可以設置快捷方式對象的屬性,例如目標路徑(TargetPath
)、圖標路徑(IconLocation
)等,最后保存快捷方式(Save
)。
別人的方法:
在C#中,可以使用System.IO
命名空間下的FileSystem
類來創建快捷方式。下面是一個示例代碼:
csharp復制插入
using System;
using System.IO;
using IWshRuntimeLibrary;namespace ShortcutDemo
{class Program{static void Main(string[] args){string targetPath = @"C:\Path\To\Your\File.txt";string shortcutPath = @"C:\Path\To\Your\Shortcut.lnk";CreateShortcut(targetPath, shortcutPath);Console.WriteLine("Shortcut created successfully!");}static void CreateShortcut(string targetPath, string shortcutPath){WshShell shell = new WshShell();IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);shortcut.TargetPath = targetPath;shortcut.Save();}}
}
上述代碼中,CreateShortcut
方法接受兩個參數,分別是目標文件路徑和快捷方式路徑。在CreateShortcut
方法中,我們首先創建了一個WshShell
對象,然后使用CreateShortcut
方法創建了一個IWshShortcut
對象。接著,我們設置shortcut.TargetPath
為目標文件路徑,并保存快捷方式。
我的方法:
?先附圖:
CPL文件與DLL文件類似,都具有“導出函數”,在appwiz.cpl(用于管理已安裝的程序和功能。通過運行appwiz.cpl,用戶可以打開“程序和功能”窗口,該窗口允許用戶查看、更改或卸載已安裝的程序。)中,有一個函數:“NewLinkHereW”可以實現我們的要求
?[DllImport("appwiz.cpl", SetLastError = true, CharSet = CharSet.Unicode)]
?public static extern int NewLinkHereW(
? IntPtr hwndCpl,
? int msg,
? string lParam1,
? string lParam2
);
這個函數的簽名是CPL文件標準方式來寫的,一般我們需要提供四個參數。
應用:
要想成功發起該對畫框,創建一個文件,函數將刪除這個文件并在這個文件原位置上建立快捷方式
NewLinkHereW(0,0,"創建的文件地址",null);