C#,shell32 + 调用控制面板项(.Cpl)实现“新建快捷方式对话框”(全网首发)

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

相关推荐
ZEERO~几秒前
@dataclass的作用
开发语言·windows·python
南行*8 分钟前
C语言Linux环境编程
linux·c语言·开发语言·网络安全
Morwit10 分钟前
Qt qml创建c++类的单例对象
开发语言·c++·qt
古城小栈13 分钟前
Rust 已经自举,却仍需GNU与MSVC工具链的缘由
开发语言·rust
雪域迷影15 分钟前
Windows11上安装Redis服务和Redis可视化客户端
windows·redis
广然16 分钟前
Windows 11 关闭 VBS 的几种方法
windows·ensp·vbs
jarreyer17 分钟前
数据项目分析标准化流程
开发语言·python·机器学习
不染尘.19 分钟前
Linux基本概述
linux·windows·centos·ssh
你怎么知道我是队长20 分钟前
C语言---printf函数使用详细说明
c语言·开发语言
liulilittle22 分钟前
俄罗斯访问欧洲国际线路优化
开发语言·网络·信息与通信·ip·通信·俄罗斯·莫斯科