c#checked listbox MouseMove vs MouseHover事件处理程序

时间:2009-10-11 06:41:29

标签: .net winforms checkedlistbox mousemove mousehover

我正在使用以下MouseMove事件处理程序将文本文件内容显示为CheckedListBox上的工具提示,并且每个checkedListBoxItem都标记了一个文本文件对象。

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

这类问题可以解决什么问题?

2 个答案:

答案 0 :(得分:5)

在MouseHover事件中,您可以使用Cursor.Position property并将其转换为客户端位置并传递给IndexFromPoint()以确定它包含在哪个列表项中。

例如

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

这也适用于其他事件,在事件参数中没有给出鼠标位置。

答案 1 :(得分:1)

问题是因为SelectedItem<> checkedItem,selected表示有另一个背景,checked表示在左侧检查。

而不是

 int index = chk.SelectedIndex;

你应该使用:

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

然后显示你想要的东西......