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

相关推荐
zhangfeng113314 分钟前
台大李宏毅老师讲解memba和类似linear atttenion 模型,笔记
开发语言·人工智能·笔记
Chris _data1 小时前
并发单词频率统计器 - 从零到完整实现(C# 实战)
开发语言·c#
idolao1 小时前
Oligo 7.60 安装教程:引物设计+Java 环境配置
java·开发语言
不知名的老吴1 小时前
Lambda表达式与新的Streams API相结合
开发语言·python
石山代码8 小时前
ArrayList / HashMap / ConcurrentHashMap
java·开发语言
程序大视界8 小时前
【Python系列课程】Python正则表达式(下):环视、命名分组与日志实战
开发语言·python·正则表达式
jingshaoqi_ccc9 小时前
windows 10系统下QT的安装及在Visual studio中的扩展安装
windows·qt·visual studio
枫叶v.9 小时前
Agent 分层存储架构设计:从记忆方法到中间件选型
开发语言·python
sleven fung10 小时前
MinerU与BabelDOC与KTransformers与OpenAI API库
开发语言·python·ai·langchain
萤萤七悬10 小时前
【Python笔记】AI帮实现CLI工具-使用argparse.ArgumentParser接收命令参数
开发语言·笔记·python