[C#]將程式加入右鍵選單
一、問題描述
如何將程式加入右鍵選單?
二、方法
透過寫入登錄檔的方式
針對檔案右鍵選單,在 HKEY_CLASSES_ROOT\*\shell
針對目錄又見選單,在 HKEY_CLASSES_ROOT\Directory\shell
針對寫入登錄檔,使用 RegistryKey 類別 : 表示 Windows 登錄中的機碼層級節點。 這個類別的作用是登錄封裝。
參考以下程式碼
private void btnReg_Click(object sender, EventArgs e)
{
string sText = this.Text;
string sFullName = string.Format("{0} %1", Application.ExecutablePath);
// Application.ExecutablePath 是程式執行檔的完整路徑檔案名稱
// %1 表示傳入的檔案
if (this.rbFile.Checked)
{
// 加入檔案右鍵選單
RegFile(sText, sFullName);
}
else
{
// 加入目錄右鍵選單
RegDirectory(sText, sFullName);
}
MessageBox.Show("作業成功");
}
private void RegFile(string sText, string sFullName)
{
RegistryKey shell = Registry.ClassesRoot.OpenSubKey(@"*\shell", true);
RegistryKey custom = shell.CreateSubKey(sText);
RegistryKey cmd = custom.CreateSubKey("command");
cmd.SetValue(string.Empty, sFullName);
cmd.Close();
custom.Close();
shell.Close();
}
private void RegDirectory(string sText, string sFullName)
{
RegistryKey shell = Registry.ClassesRoot.OpenSubKey(@"directory\shell", true);
RegistryKey custom = shell.CreateSubKey(sText);
RegistryKey cmd = custom.CreateSubKey("command");
cmd.SetValue("", sFullName);
cmd.Close();
custom.Close();
shell.Close();
}
三、執行結果
程式介面
選擇 [檔案],按 [執行],加入檔案右鍵選單
選擇 [目錄],按 [執行],加入目錄右鍵選單
四、範例下載
由於寫入登錄檔需要權限,因此請在編譯好的執行檔上,按滑鼠右鍵,選擇 [以系統管理員身分執行]



