Selecting item under mouse cursor in CheckedListBox

AndersLiden

New member
Joined
Sep 3, 2007
Messages
2
Programming Experience
10+
I want to right click an item in a CheckedList box and get a small menu appearing when I do, but I just cant seem the find the documentation for selecting an item at specific mouse cursors.

My problem:
If I check the item in the CheckedListBox and then press right mouse button I have no problem, it selects the correct item, but if I only press the right mouse button over an item it will not select that item but another item in the checkedlistbox that is checked or nothing at all.

My solution:
Check the item under the mouse cursor and then show the menu.

But, alas, I cant seem to find how to check the item under the mouse cursor.

Help?

// Anders Liden
Gothenburg, Sweden.
 
It is easy to toggle item check with right mouse button using the IndexFromPoint method, but you shouldn't do it because a Windows user does not expect an item to be checked with right mouse button, that button is only used to get a context menu. So consider your application design. You can still store information about what item (index) the user called the context menu for, and use this information to handle the context menu request. But I don't think you should impose an unrequested checked state toggle. Example:
VB.NET:
    Private Sub CheckedListBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) _
    Handles CheckedListBox1.MouseDown
        If e.Button = Windows.Forms.MouseButtons.Right Then
            contextIndex = CheckedListBox1.IndexFromPoint(e.Location)
        End If
    End Sub

    Private contextIndex As Integer

    Private Sub TestToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles TestToolStripMenuItem.Click
        MsgBox("you called context menu on item index " & contextIndex)
    End Sub
 
Thanks a lot for you help. Of course I should not check the item if I don't need to, you are absolutely right. It was mainly the IndexFromPoint function I needed.

Thanks a lot!

// Anders Liden
Gothenburg, Sweden
 
Back
Top