通过SharpShell快速实现Windows Shell扩展

在.NET 4引入了CLR in-process side-by-side特性后,我们也可以通过C#编写Windows Shell了。我们可以在微软的All-In-One Code Framework里面找到相关示例,在院子里也有几篇文章介绍它:

但是,研究过这些示例后便会发现:虽然用C#编写Shell扩展比用C++简单不少,但仍然比较繁琐,有许多需要注意的地方,一不小心就会出错

今天,在CodePlex上发现了一个SharShell的项目,通过它可以快速创建Shell扩展,非常方便。例如,对如如下的一个菜单扩展:

    通过SharpShell快速实现Windows Shell扩展

只需要用如下几句话就能实现:

    [ComVisible(true)]
    [COMServerAssocation(AssociationType.ClassOfExtension, ".txt")]
    public class CountLinesExtension : SharpContextMenu
    {
        protected override bool CanShowMenu()
        {
            return true;
        }

        protected override ContextMenuStrip CreateMenu()
        {
            var menu = new ContextMenuStrip();
            var itemCountLines = new ToolStripMenuItem
            {
                Text = "Count Lines...",
                Image = Properties.Resources.CountLines
            };

            itemCountLines.Click += (sender, args) => CountLines();
            menu.Items.Add(itemCountLines);
            return menu;
        }

        private void CountLines()
        {
            var builder = new StringBuilder();
            foreach (var filePath in SelectedFilePaths)
            {
                builder.AppendLine(string.Format("{0} - {1} Lines", Path.GetFileName(filePath), File.ReadAllLines(filePath).Length));
            }
            MessageBox.Show(builder.ToString());
        }
    }

更多信息可以参看CodeProject上的入门教程:.NET Shell Extensions - Shell Context Menus

 

你可能感兴趣的:(windows)