winforms - 在 Winform 应用程序上启用拖放
问题描述
我想为我的 winforms 应用程序启用拖放功能。主 UI 窗体是一个 MDI 容器。
我在主窗体中添加了以下代码
mainuiform.AllowDrop = true;
mainuiform.DragDrop += OnDragDrop;
mainuiform.DragEnter += OnDragEnter;
拖放在应用程序的主体中不起作用,仅在应用程序的标题上起作用。
然后我读到应该为每个子组件启用拖放功能,然后我们才能将文档拖放到应用程序 ui 上的任何位置。这很痛苦,因为 MDI 中的各种表格是由不同的团队创建的。
我如何实现这一目标?
解决方案
- 将事件处理程序添加到主窗体(构造函数)
- 将事件处理程序添加到主窗体的所有子组件(在加载事件中)
- 将事件处理程序添加到 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;
}
拖放适用于使用此代码的应用程序。
推荐阅读
- ionic-framework - cordova-ios 6.xx - 如何添加对多个主机名的支持?
- powershell - 适用于多台服务器的 Powershell For Loop
- user-interface - javafx : ui 切换按钮点击
- apache-kafka - Kafka 主题 - 模式注册表兼容性
- javascript - 如何修改电子浏览器窗口中使用的 HTML 文件?
- html - 将图像添加到输入标签
- reactjs - 父组件和子组件中的 MapStateToProps 和 MapDispachToProps 不起作用
- excel - 根据单元格值为工作表中的多个形状着色
- javascript - jQuery 数据表插件没有提供想要的结果
- firebase - 如何验证电子邮件和密码flutter firebase