[英]How to use drag&drop in an async task
My goal is to drag and drop a file out of my app into a dropzone of a website.我的目标是将文件从我的应用程序中拖放到网站的放置区中。
For that I've made this form:为此,我制作了这个表格:
public partial class Form2 : Form
{
private DataObject File;
public Form2(string filePath)
{
InitializeComponent();
File = new DataObject();
File.SetFileDropList(new StringCollection() { filePath });
labelFileName.Text = Path.GetFileName(filePath);
}
private void labelFileName_MouseDown(object sender, MouseEventArgs e)
{
labelFileName.DoDragDrop(File, DragDropEffects.Copy);
}
}
It works if I use it like this:如果我像这样使用它,它会起作用:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var form2 = new Form2("C:\\testfile.txt");
form2.ShowDialog();
}
}
But drag and drop dosn't work if I use it in an async Task like this:但是,如果我在这样的异步任务中使用它,拖放将不起作用:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private async void buttonRunAsync_Click(object sender, EventArgs e)
{
await Task.Run(() => OpenForm2());
}
private async Task OpenForm2()
{
var form2 = new Form2("C:\\testfile.txt");
form2.ShowDialog();
// do some stuff based on dialog result
}
}
I think that's because it's not running in the UI thread but I haven't found a good explanation and also I'm not sure if that's the problem.我认为那是因为它没有在 UI 线程中运行,但我没有找到很好的解释,而且我不确定这是否是问题所在。
Using Invoke like this fixed my problem:像这样使用 Invoke 解决了我的问题:
private async Task OpenForm2()
{
this.Invoke((MethodInvoker)delegate
{
var form2 = new Form2("C:\\testfile.txt");
var result = form2.ShowDialog();
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.