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);