Search code examples
c#winformsdrag-and-droplistbox

how to highlight the "hovered" item when dragging the item inside listbox


I would like to highlight the hovered item when dragging the item inside ListBox

I find one related question here, but when mouse is pressed, the MouseMove and MouseLeave event stop working.


Solution

  • When the mouse is captured by another control, mouse event's like MouseMove will not raise for the drop target control.

    Regardless of the mouse capture, you always can find the hot index using the following code:

    var index = listBox1.IndexFromPoint(listBox1.PointToClient(Cursor.Position));
    

    If the mouse enter/move/leave events during the drag is important for you, use drag events DragEnter, DragOver and DragLeave events.

    For example, to get the index of the item under the mouse pointer when the mouse is dragging over the target listbox, you can handle DragOver:

    private void listBox1_DragOver(object sender, DragEventArgs e)
    {
        var index = listBox1.IndexFromPoint(listBox1.PointToClient(Cursor.Position));
    }