【问题标题】:How to display the ContextMenuStrip when item is selected in a list box c# .net如何在列表框中选择项目时显示 ContextMenuStrip c# .net
【发布时间】:2016-06-08 18:41:43
【问题描述】:

我试图在右键单击时从列表框中选择一个项目并显示 ContextMenuStrip 以显示我的可用选项,但是当我单击控件(列表框)中的任何位置时都显示 ContextMenuStrip。

这是我在代码中的内容:

private void lbSMTPEmails_MouseDown(object sender, MouseEventArgs e)
{       
       int SelectedIndex = lbSMTPEmails.IndexFromPoint(e.X, e.Y);

       if (SelectedIndex == -1)
            lbSMTPEmails.ContextMenuStrip.Hide();            
        else
        {
            lbSMTPEmails.SelectedIndex = SelectedIndex;
            lbSMTPEmails.ContextMenuStrip.Show();
        }
}

你知道如何解决这个问题吗?

【问题讨论】:

  • 这段代码对我有用!当我在列表框中选择任何项目时,它会向我显示 contextmenustrip,当您在列表框中单击(不再选择任何项目)时,它不会为我显示 contextmenustrip!
  • 不知道为什么不起作用,我找到了另一个解决方案,我会在这里发布。

标签: c# .net listbox contextmenustrip listboxitems


【解决方案1】:

使用ContextMenuStripopening事件

void cms_Opening(object sender, System.ComponentModel.CancelEventArgs e)
{
    int SelectedIndex = lbSMTPEmails.IndexFromPoint( lbSMTPEmails.PointToClient(Cursor.Position) );

   if (SelectedIndex == -1)
        e.Cancel = true;        
    else
    {
        lbSMTPEmails.SelectedIndex = SelectedIndex;            
    }
}

【讨论】:

    【解决方案2】:

    我就是这样做的,效果很好!

    private void listbox_MouseDown(object sender, MouseEventArgs e)
    {
        ShowMenuStrip = listbox.IndexFromPoint(e.Location) >= 0; //This is a global bool variable
    
        if (ShowMenuStrip)
           listbox.SelectedIndex = listbox.IndexFromPoint(e.Location);
        else
           listbox.SelectedIndex = -1;          
    }
    
    private void ContextMenuStrip_Opening(object sender, CancelEventArgs e)
    {
        e.Cancel = !ShowMenuStrip;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多