c# - 在 Excel 中执行拖放操作时 DragDrop.DoDragDrop 不返回

标签 c# excel drag-and-drop

我的应用程序有一个简单的功能,它连接到 Excel 并在它们之间进行拖放操作。具体来说,我只是从我的应用程序中获取一些文本值,将它们拖到 Excel 中,然后放下。

这在 90% 的时间都有效,但奇怪的是,在某些时候,我的应用程序只是卡住。我附加调试器并暂停执行,它卡在 DragDrop.DoDragDrop - 此函数永远不会返回,我的应用程序将永远挂起。

有没有办法确保 DoDragDrop 可以返回?或者某种超时?这种情况只有在我将数据放入 Excel 时才会发生,因此据我所知,数据放入已经完成,该函数应该会在我的应用程序中返回。

这是我使用的代码:

DragDrop.DoDragDrop(sender as DependencyObject, draggable.GetDragDropString(), DragDropEffects.Copy);

GetDragDropString() 只是一个函数,它返回要在 Excel 中放置的数据字符串。 sender 只是我正在拖动的 UI 组件。像网格、编辑框、文本框等。可以是其中任何一种。

感谢您的帮助!

编辑:由于在某些情况下 DragDrop.DoDragDrop 返回存在问题,也许有人可以帮助编写适当的超时?我已经尝试启动一个新的 Thread 并让它超时,这在简单的情况下以及线程内的工作不需要 UI 资源时有效。但是,当我在超时的新线程中调用 DoDragDrop 时,它会抛出异常,指出该线程无法访问该对象,因为另一个线程拥有它。所以我需要在同一个线程中调用这个函数。所以本质上,当此函数无法在特定时间内返回时,我需要在 UI 线程上超时。

最佳答案

我认为以下内容应该可以完成这项工作,但我会在进行过程中对其进行分解

public class DragDropTimer
{
    private delegate void DoDragDropDelegate();
    private System.Timers.Timer dragTimer;
    private readonly int interval = 3000;

    public DragDropTimer()
    {
        dragTimer = new System.Timers.Timer();
        dragTimer.Interval = interval;
        dragTimer.Elapsed += new ElapsedEventHandler(DragDropTimerElapsed);
        dragTimer.Enabled = false;
        dragTimer.AutoReset = false;
    }

    void DragDropTimerElapsed(object sender, ElapsedEventArgs e)
    {
        Initiate();
    }

    public void Initiate()
    {
        // Stops UI from freezing, call action async.
        DoDragDropDelegate doDragDrop = new DoDragDropDelegate(DragDropAction);

        // No async callback or object required
        doDragDrop.BeginInvoke(null, null);
    }

    private void DragDropAction()
    {
        dragTimer.Enabled = false; 

        // Do your work here. or do work before and disable your timer upto you.

    }

}

所以我们有一个基本类DragDropTimer。我们在构造函数上设置了我们想要的间隔,如果您愿意,您可能想要更改它,我们在计时器结束时调用 DragDropTimerElapsed

Initiate 是开始拖动所需的函数,它创建了一个简单的委托(delegate),我们要求它执行 DragAction 步骤,这是您执行所有操作的地方工作并且定时器被禁用。只有当拖放成功时,您才可以选择禁用计时器。如果计时器超时,我们会再次调用 Initiate 重新开始。

关于c# - 在 Excel 中执行拖放操作时 DragDrop.DoDragDrop 不返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35157904/

相关文章:

android - 在 android 中跨布局拖放

c# - 为什么 Mono 运行简单方法的速度较慢,而 RyuJIT 运行速度明显更快?

javascript - HTML5 拖放至 ActionScript 文件引用

c# - DataGridView 绑定(bind)问题 : "Index -1 does not have a value."

vba - 如果语句在 Excel VBA 中不起作用

excel - 在 VBA 中优化 HTML 解析

mysql - 如何在没有安装 office 的情况下从 winform vb.net 2008 导出到 excel?

angularjs - jqyoui-draggable 中的 Angular 拖放传递参数

c# - 如何检测第一次运行 ClickOnce 部署的应用程序?

c# - 如何从 html 输入按钮单击调用 Windows Phone 8 代码隐藏方法