Disabling “Drag Selection” on ListBox

牧云@^-^@ 提交于 2019-12-07 17:58:37

I guess if you call DoDragDrop this behavior would disappear. Windows doesn't dispatch MouseOver messages while in drag&drop mode.

Example of propper drag&drop:

    private void listBox_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) 
    {
        // Get the index of the item the mouse is below.
        indexOfItemUnderMouseToDrag = listBox.IndexFromPoint(e.X, e.Y);

        if (indexOfItemUnderMouseToDrag != ListBox.NoMatches) {

            // Remember the point where the mouse down occurred. The DragSize indicates
            // the size that the mouse can move before a drag event should be started.                
            Size dragSize = SystemInformation.DragSize;

            // Create a rectangle using the DragSize, with the mouse position being
            // at the center of the rectangle.
            dragBoxFromMouseDown = new Rectangle(new Point(e.X - (dragSize.Width /2),
                                                           e.Y - (dragSize.Height /2)), dragSize);
        } else
            // Reset the rectangle if the mouse is not over an item in the ListBox.
            dragBoxFromMouseDown = Rectangle.Empty;

    }

    private void listBox_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) {
        // Reset the drag rectangle when the mouse button is raised.
        dragBoxFromMouseDown = Rectangle.Empty;
    }

    private void listBox_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) 
    {
        if ((e.Button & MouseButtons.Left) == MouseButtons.Left) {

            // If the mouse moves outside the rectangle, start the drag.
            if (dragBoxFromMouseDown != Rectangle.Empty && 
                !dragBoxFromMouseDown.Contains(e.X, e.Y)) 
            {
                    DragDropEffects dropEffect = listBox.DoDragDrop(listBox.Items[indexOfItemUnderMouseToDrag], DragDropEffects.All | DragDropEffects.Link);

                    // If the drag operation was a move then remove the item.
                    if (dropEffect == DragDropEffects.Move) {                        
                        listBox.Items.RemoveAt(indexOfItemUnderMouseToDrag);

                        // Selects the previous item in the list as long as the list has an item.
                        if (indexOfItemUnderMouseToDrag > 0)
                            listBox.SelectedIndex = indexOfItemUnderMouseToDrag -1;

                        else if (ListDragSource.Items.Count > 0)
                            // Selects the first item.
                            listBox.SelectedIndex =0;
                    }
                }
            }
        }
    }

...and SelectedIndexChanged still works!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!