【问题标题】:Enable drag drop on a winform application在 Winform 应用程序上启用拖放
【发布时间】:2020-04-05 22:14:07
【问题描述】:
我想为我的 winforms 应用程序启用拖放功能。主 UI 表单是一个 MDI 容器。
我在主窗体中添加了以下代码
mainuiform.AllowDrop = true;
mainuiform.DragDrop += OnDragDrop;
mainuiform.DragEnter += OnDragEnter;
拖放在应用程序的主体中不起作用,仅在应用程序的标题上起作用。
然后我读到应该为每个子组件启用拖放功能,然后我们才能将文档拖放到应用程序 ui 上的任何位置。这很痛苦,因为 MDI 中的各种表格是由不同的团队创建的。
我如何做到这一点?
【问题讨论】:
标签:
winforms
drag-and-drop
mdi
【解决方案1】:
- 将事件处理程序添加到主窗体(构造函数)
- 向主窗体的所有子组件添加事件处理程序(在加载事件中)
- 向 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;
}
使用此代码拖放在应用程序上工作。