c# - 拖放时吞下异常

标签 c# winforms exception drag-and-drop

我有一个 WinForms 应用程序,我在其中进行 2 个 TreeView 之间的拖放操作。

在某些时候,我想拒绝底层业务实现中的操作,所以我抛出一个异常。我可以在“输出”窗口中看到异常,但问题是我在 UI 中看不到它并且它没有崩溃。

异常去哪儿了?

下面是一些描述问题的代码:

private TreeView tvLeft;
private TreeView tvRight;
private Dictionary<string, int> dico = new Dictionary<string, int>();

void tvLeft_DragDrop(object sender, DragEventArgs e) {

  if (e.Data.GetDataPresent(typeof(TreeNode))) {

    var tnSource = (TreeNode) e.Data.GetData(typeof(TreeNode));
    var tnDestination = tvLeft.GetNodeAt(tvLeft.PointToClient(new Point(e.X, e.Y)));

    // if I drag-drop the same node twice, there sould be an Exception
    // since the key is already in the dictionary...
    // ...but I get no Exception in the UI, the Application.ThreadException
    // or Appomain.CurrentDomain.UnhandledException handlers
    dico.Add(tnSource.Name, (new Random()).Next());

  }

}

最佳答案

我在网上找到了这个解释:

Even with drag-and-drop within the same application, the drag-and-drop is handled through the standard OLE drag-drop mechanism. From OLE's point of view it's dealing with two applications, the source and the target and decouples them appropriately. Since OLE has been around far longer than .NET, OLE has no concept of a .NET exception and therefore can't communicate an exception from the target back to the source. Even if it could, why should the source care that the target couldn't perform the drop? If you want to handle an exception during a DragDrop event you must handle it within your DragDrop event handler, it won't propagate beyond that event handler because there is a managed to unmanaged to managed code transition between the source and the target.

参见 here问题后的第一个答案。

关于c# - 拖放时吞下异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/969983/

相关文章:

c# - 从复选框列表中删除所选内容

c# - CaSTLeWindsor LifeStyle.PerWebRequest 表现得像单例

c# - Name For 在编辑器模板中遍历集合时生成不正确的名称

c# - 如何获取每个表单的Text属性

c# - 任务栏通知发光

.net - Silverlight 对比WPF 对比Winforms 有什么特别适合我的目的?

python - 异常处理 : what exception to raise

从 Applet 调用 Web 服务时出现 java InvokingTargetException

c# - 如何创建一个有边框但没有标题栏的表单? (如 Windows 7 上的音量控制)

asp.net - Response.Redirect - 使用异常进行流量控制?