如何在Windows资源管理器空白处添加自定义右键菜单选项?
刚好做过类似的需求,两种方案都给你整理好了,保证只在资源管理器空白区域显示自定义菜单,不会干扰文件、文件夹或驱动器的右键菜单:
方法一:手动修改注册表(快速实现)
这个方式不用写代码,几步就能搞定:
- 按下
Win + R组合键,输入regedit回车打开注册表编辑器 - 导航到路径:
HKEY_CLASSES_ROOT\Directory\Background\shell- 划重点:
Directory\Background这个键专门对应资源管理器文件夹窗口的空白背景区域,这就是为什么菜单只会在空白处显示的关键
- 划重点:
- 右键点击
shell项,选择「新建」→「项」,给这个新项起个名字(比如MyCustomTool) - 选中刚创建的
MyCustomTool项,在右侧双击(默认),设置你想在右键菜单显示的文本,比如「打开我的专属工具」 - (可选)如果想给菜单加图标:右键
MyCustomTool项,新建「字符串值」,命名为Icon,值设为你的图标文件路径(比如C:\Tools\myicon.ico) - 右键
MyCustomTool项,再新建一个「项」,命名为command - 选中
command项,双击右侧(默认),设置你要执行的命令(比如notepad.exe或者你的自定义程序路径) - 关闭注册表编辑器,现在右键资源管理器空白处就能看到你的自定义菜单了!
方法二:C#程序实现(适配VS2008)
如果你想用代码自动化完成(比如批量部署给其他机器),用VS2008写个控制台程序就行,适配.NET Framework 2.0/3.5:
using Microsoft.Win32; using System; namespace ExplorerBackgroundMenu { class Program { static void Main(string[] args) { // 可自定义的参数 string menuKeyName = "MyCustomTool"; string menuDisplayText = "打开我的专属工具"; string targetCommand = @"C:\Path\To\Your\Application.exe"; string menuIconPath = @"C:\Path\To\Your\Icon.ico"; // 可选,留空则不显示图标 try { // 创建菜单的注册表项 using (RegistryKey menuKey = Registry.ClassesRoot.CreateSubKey(@"Directory\Background\shell\" + menuKeyName)) { if (menuKey != null) { menuKey.SetValue("", menuDisplayText); // 设置菜单显示文本 if (!string.IsNullOrEmpty(menuIconPath)) { menuKey.SetValue("Icon", menuIconPath); // 设置图标 } } // 创建命令执行项 using (RegistryKey commandKey = Registry.ClassesRoot.CreateSubKey(@"Directory\Background\shell\" + menuKeyName + @"\command")) { if (commandKey != null) { commandKey.SetValue("", targetCommand); // 设置要执行的命令 } } Console.WriteLine("自定义右键菜单添加成功!"); } } catch (Exception ex) { Console.WriteLine("操作出错:" + ex.Message); } Console.WriteLine("按任意键退出..."); Console.ReadKey(); } } }
注意事项:
- 程序必须以管理员权限运行,否则没有修改注册表的权限
- 如果要删除这个菜单,只需要打开注册表,删除
HKEY_CLASSES_ROOT\Directory\Background\shell下对应的MyCustomTool项即可 - 在VS2008中创建「控制台应用程序」,直接粘贴代码,修改参数就能编译运行
内容的提问来源于stack exchange,提问作者Vishal




