Why is my form going to background on DragDrop?

拥有回忆 提交于 2019-12-14 03:19:30

问题


At the end of a drag&drop operation, I'm showing a form using ShowDialog.
Problem: When the form is closed, my main form is pushed behind any other application windows.

Code:

private void ctrl_DragDrop(object sender, DragEventArgs e) {
    // ...
    if (e.Effect == DragDropEffects.Move) {
    string name = e.Data.GetData(DataFormats.Text).ToString();
    viewHelperForm.ShowDialog(view.TopLevelControl);
    // ...
}

Question: What can I do that the main form stays on top?


回答1:


Your ShowDialog() call is blocking the DragDrop event. That is very, very bad, it gums up the drag source and make it go catatonic and unresponsive to Windows messages. This has all kinds of side-effects, like your window going catatonic as well or not getting reactivated since the D+D operation isn't completed yet.

Avoid this by only displaying the dialog after the D+D operation is completed. Elegantly done by taking advantage of the Winforms plumbing that allows posting a message to the message queue and get it processed later. Like this:

    private void ctl_DragDrop(object sender, DragEventArgs e) {
        //...
        this.BeginInvoke(new Action(() => {
            viewHelperForm.ShowDialog(view.TopLevelControl);
        }));
    }


来源:https://stackoverflow.com/questions/21406863/why-is-my-form-going-to-background-on-dragdrop

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