2012-02-10 53 views
3

我爲此嘗試了很多方法並完成了數小時的研究,但它似乎從未爲我工作。C#如何使用RightClick選擇ListBox項目?

這是我目前的代碼,我不知道爲什麼它不應該工作。

private void listBox1_MouseDown(object sender, MouseEventArgs e) 
    { 
     listBox1.SelectedIndex = listBox1.IndexFromPoint(e.X, e.Y); 
     if (e.Button == MouseButtons.Right) 
     { 
      contextMenuStrip1.Show(); 
     } 
    } 

此外,我不關心,可以刪除,我只是在尋找一種方法,使鼠標右鍵選擇我點擊該項目的上下文菜單。

任何想法?

+0

,如果你設置一個斷點在該方法中,當你按下鼠標右鍵時,它是否會點擊它?還是左邊? – 2012-02-10 14:12:21

+0

我似乎沒有碰到它 – user1194782 2012-02-10 14:15:20

+0

那麼你需要調查爲什麼你沒有擊中它。該方法綁定到組合框上的事件嗎? (通常這是由設計師在InitialiseComponent()函數中添加的) – 2012-02-10 14:17:32

回答

0

每個控件都從Control類繼承ContextMenu屬性。將上下文菜單對象分配給列表框控件的ContextMenu屬性,WinForms將自動爲您處理。

7

你近了,你只是忘了選擇項目。修復:

private void listBox1_MouseUp(object sender, MouseEventArgs e) { 
     if (e.Button == MouseButtons.Right) { 
      var item = listBox1.IndexFromPoint(e.Location); 
      if (item >= 0) { 
       listBox1.SelectedIndex = item; 
       contextMenuStrip1.Show(listBox1, e.Location); 
      } 
     } 
    } 
0
private void listBox1_MouseUp(object sender, MouseEventArgs e) 
    { 
     if (e.Button== MouseButtons.Right) 
     { 
      int nowIndex = e.Y/listBox1.ItemHeight; 
      if (nowIndex < listBox1.Items.Count) 
      { 
       listBox1.SelectedIndex = e.Y/listBox1.ItemHeight; 
      } 
      else 
      { 
       //Out of rang 
      } 
     } 
    } 

我不知道C#多,但我想:)

0

我正在處理同樣的問題。從Hans Passant的回覆中,我稍微調整了一下以獲得下面的代碼。我還發現,我根本不需要在那裏放置contextMenuStrip1.Show(listBox1, e.Location);。它被自動地呼叫給我。

(我使用Visual Studio 2010旗艦版與和編譯在.NET 4.我還證實,下面的代碼同時適用於mouseup和的MouseDown。)

private void OnMouseDown(object sender, MouseEventArgs args) 
    { 
     if (args.Button == MouseButtons.Right) 
     { 
      var item = this.IndexFromPoint(args.Location); 
      if (item >= 0 && this.SelectedIndices.Contains(item) == false) 
      { 
       this.SelectedItems.Clear(); 
       this.SelectedIndex = item; 
      } 
     } 
    } 
1
private void lstFiles_MouseDown(object sender, MouseEventArgs e) 
    { 
     if (e.Button == MouseButtons.Right) //(1) 
     { 
      int indexOfItemUnderMouseToDrag; 
      indexOfItemUnderMouseToDrag = lstFiles.IndexFromPoint(e.X, e.Y); //(2) 
      if (indexOfItemUnderMouseToDrag != ListBox.NoMatches) 
      { 
       lstFiles.SelectedIndex = indexOfItemUnderMouseToDrag; //(3) 
      } 
     } 
    } 
+0

你能添加一些關於發生什麼事情的描述嗎? – dmportella 2012-11-26 12:38:08