如何在列表框c#.net中选择项目时显示ContextMenuStrip

时间:2016-06-08 18:41:43

标签: c# .net listbox contextmenustrip listboxitems

我尝试在右键单击时从列表框中选择一个项目并显示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();
        }
}

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

2 个答案:

答案 0 :(得分:2)

使用opening

ContextMenuStrip事件
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;            
    }
}

答案 1 :(得分:1)

我是通过这种方式做到的并且有效!

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;
}