拖放问题 [英] Issue with drag and drop
本文介绍了拖放问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用以下代码将文件拖放到c#winforms应用程序中。我遇到的问题是DragDrop事件处理程序需要一段时间,在这段时间内,我无法使用从中拖动文件的窗口。
I use the following code to drag and drop a file into a c# winforms application. The issue I have is that the DragDrop event handler takes a while, and during this time I can't use the window from which I dragged the file. How can this be fixed?
private void FormMain_DragDrop(object sender, DragEventArgs e)
{
string[] s = (string[])e.Data.GetData(DataFormats.FileDrop, false);
// do some long operation
}
private void FormMain_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.All;
else
e.Effect = DragDropEffects.None;
}
推荐答案
您可以使用 BackgroundWorker
在不同的线程中执行所需的操作,如下所示:
You may use a BackgroundWorker
to do the operation that you need in different thread like the following :
BackgroundWorker bgw;
public Form1()
{
InitializeComponent();
bgw = new BackgroundWorker();
bgw.DoWork += bgw_DoWork;
}
private void Form1_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] s = (string[])e.Data.GetData(DataFormats.FileDrop, false);
bgw.RunWorkerAsync(s);
}
}
对于您的问题跨线程操作,请尝试使用 调用
这样的方法:
Also for your issue "cross thread operation", try to use the Invoke
Method like this :
void bgw_DoWork(object sender, DoWorkEventArgs e)
{
Invoke(new Action<object>((args) =>
{
string[] files = (string[])args;
}), e.Argument);
}
最好使用 GetDataPresent
如上。
Its better to check if the dropped items are files using GetDataPresent
like above.
这篇关于拖放问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文