2009-10-11 22 views
2

我正在使用以下MouseMove事件處理程序將文本文件內容顯示爲CheckedListBox上的工具提示,並且存在標記爲每個checkedListBoxItem的文本文件對象。c#checked listbox MouseMove vs MouseHover事件處理程序

private void checkedListBox1_MouseMove(object sender, MouseEventArgs e) 
     { 
      int itemIndex = checkedListBox1.IndexFromPoint(new Point(e.X, e.Y)); 

      if (itemIndex >= 0) 
      { 
       if (checkedListBox1.Items[itemIndex] != null) 
       { 
        TextFile tf = (TextFile)checkedListBox1.Items[itemIndex]; 

        string subString = tf.JavaCode.Substring(0, 350); 

        toolTip1.ToolTipTitle = tf.FileInfo.FullName; 
        toolTip1.SetToolTip(checkedListBox1, subString + "\n... ... ..."); 
       } 
      } 
     } 

問題是,我的應用程序正在減速,因爲checkedListBox上頻繁的鼠標移動。

作爲替代方案,我想,我應該使用MouseHover事件及其處理程序。但我找不到我的musePointer當前在哪個checkedListBoxItem上。就像這樣:

private void checkedListBox1_MouseHover(object sender, EventArgs e) 
     { 
      if (sender != null) 
      { 
       CheckedListBox chk = (CheckedListBox)sender; 

       int index = chk.SelectedIndex; 

       if (chk != null) 
       { 
        TextFile tf = (TextFile)chk.SelectedItem; 

        string subString = tf.FileText.Substring(0, 350); 

        toolTip1.ToolTipTitle = tf.FileInfo.FullName; 
        toolTip1.SetToolTip(checkedListBox1, subString + "\n... ... ..."); 
       } 
      } 
     } 

這裏int index將返回-1,chk.SelectedItem將返回null

什麼可以解決這類問題?

回答

5

在MouseHover事件,你可以使用Cursor.Position property和轉換它傳遞給客戶端並傳遞給IndexFromPoint()以確定它包含在哪個列表項中。

例如。

Point ptCursor = Cursor.Position; 
ptCursor = PointToClient(ptCursor); 
int itemIndex=checkedTextBox1.IndexFromPoint(ptCursor); 
... 
... 

這是其他事件也,你在哪裏,未在事件參數的鼠標位置是有用的。

1

問題是因爲SelectedItem <> checkedItem,選中表示有另一個背景,選中表示檢查左邊。

,而不是

int index = chk.SelectedIndex; 

你應該使用:

int itemIndex = checkedListBox1.IndexFromPoint(new Point(e.X, e.Y)); 
bool selected = checkedListBox1.GetItemChecked(itemIndex); 

然後告訴你想要什麼,如果它選擇...

+0

這隻適用於證明MouseEventArgs事件參數的事件。它在MouseHover中不起作用。 – Ash 2009-10-11 07:09:08