Issue with drag and drop

一笑奈何 提交于 2019-12-13 11:05:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!