winforms 在C#中为ContextMenuStrip动态生成ToolStripItems

zpqajqem  于 2022-12-14  发布在  C#
关注(0)|答案(1)|浏览(183)

我有3个文件夹,其中包含一堆子文件夹和文件。我需要创建一个ContextMenuStrip,所有的文件夹和文件作为ToolStripMenuItems(作为一个树层次结构)。我知道如何硬编码它:

public class CustomApplicationContext : ApplicationContext
    {
        private NotifyIcon trayIcon;
        private ContextMenuStrip contextMenuStrip = new ContextMenuStrip();
        ToolStripMenuItem option1 = new ToolStripMenuItem("Option 1");
        ToolStripMenuItem option1a = new ToolStripMenuItem("Option 1a");
        ToolStripMenuItem option1b = new ToolStripMenuItem("Option 1b");
        ToolStripMenuItem option1c = new ToolStripMenuItem("Option 1c");
        ToolStripMenuItem option1ca = new ToolStripMenuItem("Option 1ca");
        ToolStripMenuItem option2 = new ToolStripMenuItem("Option 2");
        ToolStripMenuItem option3 = new ToolStripMenuItem("Option 3");
        ToolStripMenuItem option4 = new ToolStripMenuItem("Option 4");

        public CustomApplicationContext()
        {
            contextMenuStrip.Items.AddRange(new ToolStripItem[]
            {
                this.option1,
                this.option2,
                this.option3,
                this.option4
            });
            this.option1.DropDownItems.AddRange(new ToolStripItem[]
            {
                this.option1a,
                this.option1b,
                this.option1c
            });
            this.option1c.DropDownItems.AddRange(new ToolStripItem[] 
            {
                this.option1ca
            });
            trayIcon = new NotifyIcon()
            {
                Icon = Resources.AppIcon,
                ContextMenuStrip = contextMenuStrip,
                Visible = true
            };
        }
    }

然而,我想让它更动态,所以如果在其中一个文件夹内的东西改变,它也将动态改变。
我怎么能做到呢?

zbsbpyhn

zbsbpyhn1#

它可以通过递归方法来完成,该方法递归地遍历目录树。

private static void AddMenuItemsRecusively(
    DirectoryInfo root, 
    ToolStripItemCollection itemCollection)
{
    FileInfo[] files = root.GetFiles("*.*");
    if (files != null) {
        foreach (FileInfo fi in files) {
            itemCollection.Add(new ToolStripMenuItem(fi.Name));
        }

        DirectoryInfo[] subDirs = root.GetDirectories();
        foreach (DirectoryInfo dirInfo in subDirs) {
            var menuItem = new ToolStripMenuItem(dirInfo.Name);
            itemCollection.Add(menuItem);
            AddMenuItemsRecusively(dirInfo, menuItem.DropDownItems);
        }
    }
}

由于我们必须能够将菜单项添加到ContextMenuStrip.Items以及ToolStripMenuItem.DropDownItems,因此我们将ToolStripItemCollection传递给该方法。
我们使用baseDir作为包含基目录的DirectoryInfo创建如下菜单结构。

AddMenuItemsRecusively(baseDir, contextMenuStrip.Items);

如果要重复填充上下文菜单,请在添加菜单项之前调用contextMenuStrip.Items.Clear();

相关问题