C#通过调用SharpShell实现自定义系统右键菜单
SharpShell 是通过对Windows Shell 封装来实现.net 的调用
https://github.com/dwmkerr/sharpshell
根据官方的Demo修改的复制文件路径功能
创建类库 ShellExtension
namespace ShellExtension
{
// <summary>
// 动态添加系统右键菜单
// </summary>
[ComVisible(true)]
[COMServerAssociation(AssociationType.AllFiles)]
[COMServerAssociation(AssociationType.Directory)]
[COMServerAssociation(AssociationType.DesktopBackground)]
[COMServerAssociation(AssociationType.DirectoryBackground)]
[COMServerAssociation(AssociationType.Folder)]
public class DynamicSubMenuExtension : SharpContextMenu
{
//创建的菜单
private ContextMenuStrip menu = new ContextMenuStrip();
/// <summary>
/// 是否显示菜单
/// </summary>
protected override bool CanShowMenu()
{
this.UpdateMenu();
return true;
}
protected override ContextMenuStrip CreateMenu()
{
menu.Items.Clear();
this.MenuDefault();
if (SelectedItemPaths.Count() > 0)
{
FileAttributes attr = File.GetAttributes(SelectedItemPaths.First());
//判断文件还是文件夹 也可以判断文件扩展名 甚至解析文件内容 实现类似于压缩软件的效果
if (attr.HasFlag(FileAttributes.Directory))
{
this.MenuDirectory();
}
else
{
this.MenuFiles();
}
}
return menu;
}
/// <summary>
/// 更新菜单
/// </summary>
private void UpdateMenu()
{
menu.Dispose();
menu = CreateMenu();
}
protected void MenuDefault()
{
var CopyPathMenu = new ToolStripMenuItem
{
Text = "复制路径",
Image = Image.FromFile("图片.png")
};
CopyPathMenu.Click += (sender, args) =>
{
if (SelectedItemPaths.Count() > 0)
{
var str = new StringBuilder();
foreach (var item in SelectedItemPaths)
{
str.Append(item).AppendLine();
}
Clipboard.SetText(str.ToString().Trim());
}
else
{
Clipboard.SetText(FolderPath);
}
};
menu.Items.Add(CopyPathMenu);
}
/// <summary>
/// 创建目录的菜单
/// </summary>
protected void MenuDirectory()
{
}
// <summary>
// 创建文件的菜单
// </summary>
protected void MenuFiles()
{
}
}
}
创建菜单使用和普通WindowsForms控件一样
把代码编译成dll
创建安装运用
在任意运用中写代码就可以 注意使用管理员权限
安装Dll
string path = "Dll的路径";
var regasm = new RegAsm();
var success = Environment.Is64BitOperatingSystem ?
regasm.Register64(path, true) :
regasm.Register32(path, true);
if (success)
{
MessageBox.Show("successfully");
}
else
{
MessageBox.Show("Failed");
}
卸载Dll
string path = "Dll的路径";
var regasm = new RegAsm();
var success = Environment.Is64BitOperatingSystem ?
regasm.Unregister64(path) :
regasm.Unregister64(path);
if (success)
{
MessageBox.Show("successfully");
}
else
{
MessageBox.Show("Failed");
}
ExplorerManager.RestartExplorer();
要重新编译Dll需要卸载重启文件资源管理器 否则编译会失败
图片大小要使用16*16
网友评论