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

相关推荐
a11177627 分钟前
中文优先的企业 RAG 知识库 开源项目
开发语言·开源·kotlin
破z晓33 分钟前
javascript 导出excel表
开发语言·javascript·excel
西门啐血1 小时前
上位机开发之假装有设备,使用 C# 模拟串口设备
开发语言·mongodb·c#
ask_baidu1 小时前
python实现Doris的streamLoad
开发语言·python
阿米亚波2 小时前
【C++ STL】std::unordered_multiset
开发语言·数据结构·c++·笔记·stl
丙氨酸長鏈2 小时前
[Bukkit插件开发]手持发射器箭矢机枪 教学文档 面向Python/C#开发者入门Java与Bukkit API
java·python·c#
淡海水2 小时前
12-01-YooAsset工程化-Unity资源管理规范
unity·c#·游戏引擎·yooasset
我是唐青枫2 小时前
Java ReentrantLock 实战详解:比 synchronized 更灵活的可重入锁
java·开发语言
QH139292318802 小时前
# R&S ZNB43 ZNA43 ZNA67矢量网络分析仪
开发语言·网络·php
脚踏实地皮皮晨3 小时前
003003001_Grid控件
开发语言·windows·算法·c#·visual studio