来自另一个线程的 DoDragDrop()

DoDragDrop() from another thread(来自另一个线程的 DoDragDrop())

本文介绍了来自另一个线程的 DoDragDrop()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次我想让用户拖动控件时,我都会调用该控件的 DoDragDrop.

Every time i want let the user to drag an control, i calling DoDragDrop of that control.

拖拽&drop 工作正常,但我对周围的事情有疑问:

The drag & drop works fine, but i have problem with things around:

  1. DoDragDrop 完全阻塞了表单,没有计时器事件跳转,没有处理任何绘制消息.

  1. DoDragDrop completely blocking the form, no timer events jumps, no paint messages handled.

DoDragDrop 阻止不仅用于拖动 &drop 操作,但直到目标程序完成 drop 事件(即 explorer.exe 的吸代码).依赖其他程序的代码很烂.

DoDragDrop blocking not only for the drag & drop operation, but until target program finishing with the drop event (I.E. explorer.exe's suck code). Depending on other program's code is sucks.

我想从一个新线程调用 DoDragDrop.

I thought to call DoDragDrop from a new thread.

试过这个:

Thread dragThread = new Thread(() =>
{
    Form frm = new Form();
    frm.DoDragDrop("data", DragDropEffects.All);
});

dragThread.SetApartmentState(ApartmentState.STA);
dragThread.IsBackground = true;
dragThread.Start();

但它似乎不起作用.我的意思是:当像这样从其他线程执行 DoDragDrop 时,我的程序或其他程序中的其他控件不会接收拖放消息.

but it doesn't seems to work. I mean: when doing DoDragDrop from other thread like this, other controls within my program or other programs does not receiving drag&drop messages.

还有其他解决方案吗?

推荐答案

DoDragDrop 方法会停止处理事件,直到第一个鼠标事件(例如 mouse move).所以我找到的解决方法非常简单——你只需要在调用 DoDragDrop 之前用相同的鼠标位置模拟鼠标事件:

The DoDragDrop method stops processing of events until first mouse event (for example mouse move). So the workaround I found is very simple - you just need to simulate mouse event with the same mouse position just before calling DoDragDrop:


void XYZControl_MouseDown(object sender, MouseEventArgs e)
{
    var senderControl = (Control) sender;
    ...
    Cursor.Position = senderControl.PointToScreen(new Point(e.X, e.Y));   // Workaround!
    if (DoDragDrop(senderControl, DragDropEffects.Move) == DragDropEffects.Move)
    {
    ...
    }
....
}

这篇关于来自另一个线程的 DoDragDrop()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:来自另一个线程的 DoDragDrop()

基础教程推荐