为程序添加系统上下文菜单

时间:2023-01-20 16:49:38
using System;
using System.Diagnostics;
using Microsoft.Win32;

namespace SimpleContextMenu
{
/// <summary>
/// 在注册表中注册和注销文件上下文菜单.
/// </summary>
static class FileShellExtension
{
/// <summary>
/// 注册上下文菜单
/// </summary>
/// <param name="fileType">要注册的文件类型</param>
/// <param name="shellKeyName">在注册表中显示的名称</param>
/// <param name="menuText">在上下文菜单中显示的文字</param>
/// <param name="menuCommand">被执行的命令行</param>
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);
}
}

/// <summary>
/// 注销上下文菜单.
/// </summary>
/// <param name="fileType">注销的文件类型</param>
/// <param name="shellKeyName">在注册表中注册的名称</param>
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))
{
//接收命令行参数处理
}
}
}
}

原文地址: http://www.codeproject.com/Articles/15171/Simple-shell-context-menu