问题
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;
}
回答1:
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);
}
Its better to check if the dropped items are files using GetDataPresent like above.
回答2:
You can use a background thread for this long-running operation, if it is not ui-intensive.
ThreadPool.QueueUserWorkItem((o) => /* long running operation*/)
来源:https://stackoverflow.com/questions/16373299/issue-with-drag-and-drop