How to make TabPages draggable?

前端 未结 3 1748
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-13 07:42

I\'d like to enable user to rearrange TabPages order by dragging and dropping. Moreover it\'d be cool to enable user to drag TabPages from one TabControl to another. Both th

3条回答
  •  离开以前
    2021-01-13 08:26

    Based on onx23's answer.

    using System;
    using System.Drawing;
    using System.Windows.Forms;
    
    namespace Utilities.Windows.Forms
    {
        public class DraggableTabControl : TabControl
        {
            private TabPage predraggedTab;
    
            public DraggableTabControl() {
                this.AllowDrop = true;
            }
    
            protected override void OnMouseDown(MouseEventArgs e) {
                predraggedTab = getPointedTab();
    
                base.OnMouseDown(e);
            }
    
            protected override void OnMouseUp(MouseEventArgs e) {
                predraggedTab = null;
    
                base.OnMouseUp(e);
            }
    
            protected override void OnMouseMove(MouseEventArgs e) {
                if(e.Button == MouseButtons.Left && predraggedTab != null)
                    this.DoDragDrop(predraggedTab, DragDropEffects.Move);
    
                base.OnMouseMove(e);
            }
    
            protected override void OnDragOver(DragEventArgs drgevent) {
                TabPage draggedTab = (TabPage) drgevent.Data.GetData(typeof(TabPage));
                TabPage pointedTab = getPointedTab();
    
                if(draggedTab == predraggedTab && pointedTab != null) {
                    drgevent.Effect = DragDropEffects.Move;
    
                    if(pointedTab != draggedTab)
                        swapTabPages(draggedTab, pointedTab);
                }
    
                base.OnDragOver(drgevent);
            }
    
            private TabPage getPointedTab() {
                for(int i=0; i

    (Forgive me for necro-posting.)

    UPDATE

    I've written an implementation that allows both dragging and closing tabs (configurable), it's available on Bitbucket here.

提交回复
热议问题