views:

1188

answers:

2

I am using the following MouseMove event-handler to show the text-file content as a tooltip on CheckedListBox and there is a text-file object tagged to each 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... ... ...");
                }
            }
        }

The problem is, my application is slowing down because of frequent mouse movements on the checkedListBox.

As an alternative, I thought, I should use MouseHover event and its handler. But I could not find out which checkedListBoxItem my musePointer is currently on. Like this:

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... ... ...");
                }
            }
        }

Here int index is returning -1 and chk.SelectedItem is returning null.

What can be the solution of this type of problem?

+1  A: 

The problem is because SelectedItem <> checkedItem, selected means have another background, checked means have check on the left side.

instead of

 int index = chk.SelectedIndex;

you should use:

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

then show what you want if it selected...

Wael Dalloul
This only works in events that prove the MouseEventArgs event parameter. It will not work in MouseHover.
Ash
+4  A: 

In the MouseHover event you could use the Cursor.Position property and convert it to a client position and pass to IndexFromPoint() to determine if which list item it is contained within.

eg.

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

This is useful for other events also, where you are not given the mouse position in the event parameters.

Ash