我想为我的winforms应用程序启用拖放功能。 UI的主要形式是MDI容器。
我在主表单中添加了以下代码
mainuiform.AllowDrop = true;
mainuiform.DragDrop += OnDragDrop;
mainuiform.DragEnter += OnDragEnter;
拖放操作在应用程序主体中不起作用,而仅在应用程序的标题上起作用。
然后,我读到应该为每个子组件启用拖放,然后只有我们才能将文档拖放到应用程序ui上的任何位置。这是痛苦的,因为MDI中的各种形式是由不同的团队创建的。
我该如何实现?
因为我使用的是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;
}
拖放使用此代码可在应用程序上运行。