首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 登錄表實戰範例二:在「新增」右鍵選單加入自訂檔案類型

     編輯:關於C語言

目標

在桌面右鍵「新增」或總管「新增」選單中加入 .cs 檔案類型,描述為「C# 程式碼檔案」,預設以記事本開啟。

登錄表結構說明

  1. HKEY_CLASSES_ROOT\.cs:副檔名對應 ProgID(此處設為 cs)。
  2. HKEY_CLASSES_ROOT\.cs\ShellNew\NullFile:空值,啟用「新增」選單項目。
  3. HKEY_CLASSES_ROOT\cs:ProgID 定義,含友善名稱與預設圖示。
  4. HKEY_CLASSES_ROOT\cs\shell\open\command:雙擊/開啟動作的執行命令。

完整程式碼

using System;
using Microsoft.Win32;

class RegTest {
    public static void Main() {
        // 1. 副檔名關聯
        RegistryKey extKey = Registry.ClassesRoot.CreateSubKey(".cs");
        extKey.SetValue("", "cs"); // ProgID
        // 2. 啟用「新增」選單
        RegistryKey shellNew = extKey.CreateSubKey("ShellNew");
        shellNew.SetValue("NullFile", "");
        extKey.Close(); shellNew.Close();

        // 3. 定義 ProgID
        RegistryKey progKey = Registry.ClassesRoot.CreateSubKey("cs");
        progKey.SetValue("", "C# Source File");
        // 4. 設定預設圖示(使用記事本圖示索引 1)
        RegistryKey iconKey = progKey.CreateSubKey("DefaultIcon");
        iconKey.SetValue("", @"c:\windows\notepad.exe,1");
        iconKey.Close();

        // 5. 定義開啟命令
        RegistryKey cmdKey = progKey.CreateSubKey(@"shell\open\command");
        cmdKey.SetValue("", @"c:\Windows\notepad.exe ""%1""");
        cmdKey.Close(); progKey.Close();

        Console.WriteLine(".cs file type registered.");
    }
}

驗證步驟

  1. 以管理員身分執行程式(寫入 ClassesRoot 需提權)。
  2. 桌面右鍵 → 新增,應出現「C# 程式碼檔案」。
  3. 建立檔案後雙擊,應以記事本開啟。

擴充建議

  • 將 notepad.exe 替換為 VS Code、Notepad++ 等編輯器路徑。
  • 加入 PerceivedType = text 讓系統識別為文字檔。
  • 部署時建議打包為 .reg 檔或安裝腳本,避免需開發環境即可佈署。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved