C# 自定義文件圖標 雙擊啟動 (修改注冊表)


程序生成的自定義文件,比如后綴是.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 是否有值,如果有,則獲取路徑下的文件,繼續操作。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM