C# 自定义文件图标 双击启动 (修改注册表)

时间:2022-09-04 17:27:47

程序生成的自定义文件,比如后缀是.test

这种文件怎么直接启动打开程序,并打开本文件呢

1、双击打开

2、自定义的文件,有图标显示

3、自定义的文件,点击右键有相应的属性

后台代码:(如何在注册表中修改信息)

    //工具启动路径
    string toolPath = System.Windows.Forms.Application.StartupPath + "\\邮件小工具.exe";

    string extension = SptdConst.FileExtension;

    string fileType = "Email File";

    string fileContent = "text/plain";
    //获取信息
    Microsoft.Win32.RegistryKey registryKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(extension);

    if (registryKey != null && registryKey.OpenSubKey("shell") != null && registryKey.OpenSubKey("shell").OpenSubKey("open") != null &&
        registryKey.OpenSubKey("shell").OpenSubKey("open").OpenSubKey("command") != null)
    {
        var varSub = registryKey.OpenSubKey("shell").OpenSubKey("open").OpenSubKey("command");
        var varValue = varSub.GetValue("");

        if (Object.Equals(varValue, toolPath + " %1"))
        {
            return;
        }
    }
    //删除
    Microsoft.Win32.Registry.ClassesRoot.DeleteSubKeyTree(extension, false);
    //文件注册
    registryKey = Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(extension);
    registryKey.SetValue("文件类型", fileType);
    registryKey.SetValue("Content Type", fileContent);
    //设置默认图标
    Microsoft.Win32.RegistryKey iconKey = registryKey.CreateSubKey("DefaultIcon");
    iconKey.SetValue("", System.Windows.Forms.Application.StartupPath + "\\logo.ico");
    //设置默认打开程序路径
    registryKey = registryKey.CreateSubKey("shell\\open\\command");
    registryKey.SetValue("", toolPath + " %1");
    //关闭
    registryKey.Close();

 

在修改了注册表信息后,双击文件是启动了软件,之后怎么在代码中操作?

//双击启动打开
 //如果原有路径中存在空格,则会分解成多个元素
if (e.Args.Length > 0)
{
      string filePath = String.Join(" ", e.Args.ToArray());
      FileInfo file = new FileInfo(filePath);
      if (file.Exists)
       {
           EmailToolConst.DoubleClickSptdFilePath = file.FullName;
       }
  }

然后可以在主程序loaded方法中,判断DoubleClickSptdFilePath 是否有值,如果有,则获取路径下的文件,继续操作。