如何只用鼠标左键选择ListViewItem?

时间:2012-11-29 11:50:11

标签: c# winforms listview

如何通过点击和双击来阻止右键单击列表视图中的项目?

3 个答案:

答案 0 :(得分:2)

您可以使用此代码,我认为它应该完成这项工作。您需要设置一些bool变量,以指示在MouseDown中已点击鼠标右键,然后Clear个所选项目,如果由于右键单击而触发了SelectedIndexChanged事件处理程序然后重置MouseUp事件的指标。检查代码:

bool rightClicked = false;
private void listView1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == System.Windows.Forms.MouseButtons.Right)
    {
        rightClicked = true;
    }
    else
    {
        rightClicked = false;
    }
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (rightClicked)
    {
        listView1.SelectedItems.Clear();
    }

}

private void listView1_MouseUp(object sender, MouseEventArgs e)
{
    rightClicked = false;
}

编辑:这是我能做的最好的,它保留了选择但闪烁。可以使用项目的一些自定义绘图来实现解决方案,但这需要太多时间。我把它留给你。

bool rightClicked = false;
int [] lviListIndex = null;
private void listView1_MouseDown(object sender, MouseEventArgs e)
{
      if (e.Button == System.Windows.Forms.MouseButtons.Right)
      {
            rightClicked = true;
            lviListIndex = new int[listView1.SelectedItems.Count];
            listView1.SelectedIndices.CopyTo(lviListIndex, 0);
      }
      else
      {
            rightClicked = false;
      }
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
      if (rightClicked)
      {
            listView1.SelectedIndices.Clear();   
      }
}

private void listView1_MouseUp(object sender, MouseEventArgs e)
{
      if (rightClicked)
      {
            listView1.SelectedIndexChanged -= new System.EventHandler(listView1_SelectedIndexChanged);
            if (lviListIndex != null)
            {
                 foreach (int index in lviListIndex)
                 {
                      listView1.SelectedIndices.Add(index);
                 }
            }
            lviListIndex = null;
            listView1.SelectedIndexChanged += new System.EventHandler(listView1_SelectedIndexChanged);
      }
      rightClicked = false;
}

答案 1 :(得分:1)

对listview进行子类化并添加此覆盖:

protected override void WndProc(ref Message m)
        {
            const int WM_RBUTTONUP = 0x0205;
            const int WM_RBUTTONDOWN = 0x0204;

            if ((m.Msg != WM_RBUTTONDOWN) && (m.Msg != WM_RBUTTONUP))
            {
                base.WndProc(ref m);
            }
        }

这可以忽略来自鼠标右键的消息。

答案 2 :(得分:-1)

您可以像if (e.Button == MouseButtons.Left)

一样查看