【问题标题】:How can I assign a context menu to a toolstrip menu item in winform?如何将上下文菜单分配给 winform 中的工具条菜单项?
【发布时间】:2013-12-10 16:28:35
【问题描述】:

我有一个带有 ToolStripDropDownButton 的 ToolStrip,我在代码的运行时向其中添加 ToolStripMenuItems。我需要有一个默认的 ContextMenuStrip 并将其分配给每个菜单项,因此当用户右键单击一个菜单项时,他将获得该上下文菜单条。 有可能吗?

感谢您的帮助。

【问题讨论】:

  • 我没有看到任何直接的方法。Toolstripmenu 项与 contextmenuitem 非常相似。但我很确定必须有一种使用 Windows API 的方法。
  • UI 不合适。没有用户会认为右键单击菜单项会做任何事情。创建无法发现的 UI 没有意义,只需添加一个子菜单即可。

标签: winforms contextmenustrip


【解决方案1】:

好像我想出了一些有用的东西,这显然不完美,但应该给你一个不错的起点。我假设你有一个名为 contextmenustrip1 的 ContextMenuStrip,其中一些下拉项目是aaaToolStripMenuItem。然后创建一个私有布尔字段,

private static bool clickReleased=false;

aaaTool...的MouseDown事件中编写如下代码;

if (e.Button == MouseButtons.Right)
   clickReleased = true;

然后在 MouseUp 事件中,写这个;

if (e.Button == MouseButtons.Right)
   {
   if (clickReleased)
      {
        contextMenuStrip1.Show(Cursor.Position);
        clickReleased = false;
      }
   }

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    我找到了一个很好的解决方案:enter link description here

    为了节省您的阅读时间,我还在此处添加了解决方案:

    void MenuItemContext(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left) return;
    
            ToolStripMenuItem mID = (ToolStripMenuItem)sender;
    
            ContextMenu tsmiContext = new ContextMenu();
    
            MenuItem Item1 = new MenuItem();
            MenuItem Item2 = new MenuItem();
    
            Item1.Text = "Item1";
            Item2.Text = "Item2";
    
            tsmiContext.MenuItems.Add(Item1);
            tsmiContext.MenuItems.Add(Item2);
    
            Item1.Click += new EventHandler(Item1_Click);
            Item2.Click += new EventHandler(Item2_Click);
    
            hndPass = mID.Text;
    
            tsmiContext.Show(menuStrip1, menuStrip1.PointToClient(new Point(Cursor.Position.X, Cursor.Position.Y)));
        }
    
        private String hndPass;
    
        void Item1_Click(object sender, EventArgs e)
        {
           MenuItem mID = (MenuItem)sender;
            MessageBox.Show("You clicked " + mID.Text + " in the context menu of " + hndPass);
        }
        void Item2_Click(object sender, EventArgs e)
        {
            MenuItem mID = (MenuItem)sender;
            MessageBox.Show("You clicked " + mID.Text + " in the context menu of " + hndPass); ;
        }
    

    玩得开心(-:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-23
      • 2013-12-27
      • 2014-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多