C # checked listbox MouseMove vs MouseHover event handler

I am using the following event handler MouseMove

to show the content of a text file as a tooltip in a CheckedListBox, and there is a text file object marked with 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 due to frequent mouse movements on the checkedListBox.

Alternatively, I thought I should use an event MouseHover

and its handler. But I couldn't find out which checkListBoxItem 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

returns -1 and chk.SelectedItem

returns null

.

What could be the solution to this type of problem?

+2


source to share


2 answers


On the MouseHover event, you can use the Cursor.Position property and convert it to the client position and go to IndexFromPoint () to determine which list item contains.

eg.



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

      

This is useful for other events as well where you don't have a mouse position specified in the event parameters.

+5


source


The problem is that the SelectedItem <> checkedItem selected has a different background, checked means have a check on the left side.

instead

 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 selected ...

+1


source







All Articles