C# - 从ContextMenuStrip和“智能事件”中动态添加和删除项目

时间:2013-07-29 05:37:35

标签: c# winforms contextmenustrip removable-drive

简而言之,我的问题是如何实现“发送到”(右键单击Windows上的文件)

我有一个数据网格视图,其中还包含一个带有日志文件名的列(我知道每个文件的路径)

我想添加到我的弹出菜单中将选项复制到桌面和磁盘上的Key(可移动)驱动程序。

我的弹出式菜单可能如下所示:

   View log

   Open file location

   <---------------->

   Copy to -->  Desktop
                (and Removable Drivers)

   ...

所以我想:

  1. 在“复制到”子菜单下添加带有“桌面”的列表和所有可移动驱动程序(以及删除用户弹出它们的可移动驱动程序)

  2. 正如我所说,我想将文件复制到可移动驱动程序中,那么如何添加“动态事件” - 我的意思是 - 如果用户插入4个Disk On Key驱动程序,我有新的4行“复制到“子菜单(比方说,桌面和E:\,F:\,G:\,L :),所以我需要每个可移动驱动程序的新点击事件,以将文件复制到真正的驱动程序......

  3. 关于问题1 - 我发现代码检测到可移动驱动程序是否插入计算机,并且我成功将可移除驱动程序添加到子菜单。但是我没有成功删除子菜单中的项目:

    private void menu_PopUp_Opening(object sender, CancelEventArgs e)
    {
        // Need to remove all removable drivers first --> How to do ?
    
        // to update the USB drivers when opening new pop up menu
        DriveInfo[] ListDrives = DriveInfo.GetDrives();
        foreach (DriveInfo Drive in ListDrives)
        {
            if (Drive.DriveType == DriveType.Removable)
            {
                // add to popup menu, from: http://stackoverflow.com/questions/5868446/how-to-add-sub-menu-items-in-contextmenustrip-using-c4-0
                (menu_PopUp.Items[3] as ToolStripMenuItem).DropDownItems.Add(Drive.Name + " (" + Drive.VolumeLabel + ")");
            }
        }
    }
    

    谢谢你的任何帮助!

2 个答案:

答案 0 :(得分:2)

为什么不直接删除除最顶层之外的所有菜单子项,即“桌面”:

  ...
  // Need to remove all removable drivers first
  ToolStripMenuItem copyToItem = menu_PopUp.Items[3] as ToolStripMenuItem;

  // Assuming that "Desktop" menu item is the top one, 
  // we should delete all the items except #0 
  for (int i = copyToItem.DropDownItems.Count - 1; i >= 1; --i)
    copyToItem.DropDownItems.RemoveAt(i);

  ...
  // to update the USB drivers when opening new pop up menu
  DriveInfo[] ListDrives = DriveInfo.GetDrives();

  foreach (DriveInfo Drive in ListDrives) {
    if (Drive.DriveType == DriveType.Removable) {
      // add to popup menu, from: http://stackoverflow.com/questions/5868446/how-to-add-sub-menu-items-in-contextmenustrip-using-c4-0
      ToolStripItem item = (menu_PopUp.Items[3] as ToolStripMenuItem).DropDownItems.Add(Drive.Name + " (" + Drive.VolumeLabel + ")");

      item.Tag = Drive.Name; // <- bind (via tag) driver name with menu item
      item.Click += OnRemovableDriveClick;
    }
  }

...

  private void OnRemovableDriveClick(object sender, EventArgs e) {
    ToolStripItem item = sender as ToolStripItem;

    String driveName = item.Tag as String;
    ...

答案 1 :(得分:0)

  1. 参考&#34;复制到&#34;项目
  2. 循环浏览该项目的项目

    ToolStripMenuItem copyToItem = menuStrip.Item(...)

    foreach(copyToItem.Items中的ToolStripMenuItem项) {     copyToItem.Items.Remove(项目); }