using System;using System.Diagnostics;using Microsoft.Win32;namespace SimpleContextMenu{ ////// 在注册表中注册和注销文件上下文菜单. /// static class FileShellExtension { ////// 注册上下文菜单 /// /// 要注册的文件类型 /// 在注册表中显示的名称 /// 在上下文菜单中显示的文字 /// 被执行的命令行 public static void Register(string fileType, string shellKeyName, string menuText, string menuCommand) { Debug.Assert(!string.IsNullOrEmpty(fileType) && !string.IsNullOrEmpty(shellKeyName) && !string.IsNullOrEmpty(menuText) && !string.IsNullOrEmpty(menuCommand)); //创建注册表位置的完整路径 string regPath = string.Format(@"{0}\shell\{1}", fileType, shellKeyName); //注册表中添加上下文菜单 using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(regPath)) { key.SetValue(null, menuText); } //添加命令到被调用的注册表 using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(string.Format(@"{0}\command", regPath))) { key.SetValue(null, menuCommand); } } ////// 注销上下文菜单. /// /// 注销的文件类型 /// 在注册表中注册的名称 public static void Unregister(string fileType, string shellKeyName) { Debug.Assert(!string.IsNullOrEmpty(fileType) && !string.IsNullOrEmpty(shellKeyName)); // 注册表中的位置的完整路径 string regPath = string.Format(@"{0}\shell\{1}", fileType, shellKeyName); //从注册表中删除上下文菜单 Registry.ClassesRoot.DeleteSubKeyTree(regPath); } }}
调用方法:
using System;using System.Windows.Forms;using System.IO;using System.Drawing;using System.Drawing.Imaging;[assembly: CLSCompliant(true)]namespace SimpleContextMenu{ static class Program { const string FileType = "Directory"; // 注册的文件类型 const string KeyName = "Simple Context Menu"; //在注册表的上下文菜单名称 const string MenuText = "Copy to Grayscale"; // 上下文菜单文本 [STAThread] static void Main(string[] args) { // 注册右键菜单 if (!ProcessCommand(args)) { //接收命令行参数处理 } } }}原文地址: