首页 > 解决方案 > 在 Winform 应用程序上启用拖放

问题描述

我想为我的 winforms 应用程序启用拖放功能。主 UI 窗体是一个 MDI 容器。

我在主窗体中添加了以下代码

    mainuiform.AllowDrop = true;
    mainuiform.DragDrop += OnDragDrop;
    mainuiform.DragEnter += OnDragEnter;

拖放在应用程序的主体中不起作用,仅在应用程序的标题上起作用。

然后我读到应该为每个子组件启用拖放功能,然后我们才能将文档拖放到应用程序 ui 上的任何位置。这很痛苦,因为 MDI 中的各种表格是由不同的团队创建的。

我如何实现这一目标?

标签: winformsdrag-and-dropmdi

解决方案


  1. 将事件处理程序添加到主窗体(构造函数)
  2. 将事件处理程序添加到主窗体的所有子组件(在加载事件中)
  3. 将事件处理程序添加到 mdi child 及其所有子组件(MdiChildActivate 事件)

因为我使用的是 DevExpress,所以有一些 DevExpress 方法(应该与 winforms 等效)。

        public MainMdiForm() {
            RegisterDragDropEvents(this);
            MdiChildActivate += OnMdiChildActivate;
        }

        // load event handler
        private void MainMdiFormLoad(object sender, EventArgs e)
            if(sender is XtraForm form)
                form.ForEachChildControl(RegisterDragDropEvents);
        }

        private void RegisterDragDropEvents(Control control)
        {
            control.AllowDrop = true;
            control.DragDrop += OnDragDrop;
            control.DragEnter += OnDragEnter;
        }

        private void DeRegisterDragDropEvents(Control control)
        {
            control.DragDrop -= OnDragDrop;
            control.DragEnter -= OnDragEnter;
        }

        private void OnMdiChildActivate(object sender, EventArgs e)
        {
            if (sender is XtraForm form)
            {
                // since the same event is called on activate and de active, have observed that ActiveControl == null on de active
                // using the same to de register
                if (form.ActiveControl == null)
                {
                    form.ForEachChildControl(DeRegisterDragDropEvents);
                }
                else
                {
                    form.ForEachChildControl(RegisterDragDropEvents);
                }
            }
        }

        void OnDragDrop(object sender, DragEventArgs e)
        {
          // take action here
        }

        void OnDragEnter(object sender, DragEventArgs e)
        {
            // additional check and enable only when the file is of the expected type
            e.Effect = DragDropEffects.All;
        }

拖放适用于使用此代码的应用程序。


推荐阅读