本文介绍了允许在表单中的任何位置进行DragDrop的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以允许将控件拖放到充满控件的表单中的任何地方?

Is there a way to allow Drag and Drop anywhere in a form full of controls?

该想法是允许用户将文件拖放到表单中的任何位置。以加载它。我将不需要任何其他DragDrop行为。

The idea is to allow user to drag a file anywhere in a form in order to "load" it. I will not need any other DragDrop behavior but this.

仅通过将 AllowDrop = True 设置为表单,我获得 DragEnter 事件,但没有获得 DragDrop 事件。

By setting AllowDrop=True to the form only, I get DragEnter events but not DragDrop ones.

想法是在 DragEnter 上显示一个最顶面板并在那里处理 DragDrop 事件,但我想知道是否因为在该领域的经验不足而错过这里明显的东西。

An idea would be to make a topmost panel visible on DragEnter and handle DragDrop events there, but I wonder if I miss something obvious here since I have little experience in the field.

另一个想法是遍历所有控件和订阅与拖动相关的事件。但是,我真的不喜欢这种方法。

Another Idea would be to iterate through all controls and subscribe to Drag-related events. I really don't like this approach, though.

推荐答案

当然,对控件进行迭代将是可行的,并且不需要太多代码:

Sure, iterating the controls will work, it doesn't take much code:

    public Form1() {
        InitializeComponent();
        WireDragDrop(this.Controls);
    }
    private void WireDragDrop(Control.ControlCollection ctls) {
        foreach (Control ctl in ctls) {
            ctl.AllowDrop = true;
            ctl.DragEnter += ctl_DragEnter;
            ctl.DragDrop += ctl_DragDrop;
            WireDragDrop(ctl.Controls);
        }
    }

    void ctl_DragDrop(object sender, DragEventArgs e) {
        // etc..
    }

    void ctl_DragEnter(object sender, DragEventArgs e) {
        // etc..
    }

如果您仍然不喜欢这种方法,请使用可识别的单一放置目标,该目标将始终被用户击中。就像一个标有 Drop here的标签一样简单。

If you still don't like the approach then use a recognizable single drop target that the user will always hit. Could be as simple as a label that says "Drop here".

这篇关于允许在表单中的任何位置进行DragDrop的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 14:35