Winforms: Close modal dialog when clicking outside the dialog

后端 未结 5 1317
旧巷少年郎
旧巷少年郎 2020-12-17 10:08

I have an open modal dialog (Windows Forms). I want, that the dialog is closed when clicking outside the dialog (on the parent form). How can I do that?

5条回答
  •  爱一瞬间的悲伤
    2020-12-17 10:45

    Use .Show() instead of .ShowDialog().

    Handle Deactivate event in child form.

    private void frmAdvancedSearch_Deactivate(object sender, EventArgs e)
        {
            this.Close();
        }
    

    This would close the child form when user clicks outside the child.

    If you are using .ShowDialog() for doing something after the child closed, use .show() and override the 'formclosing' event of child in the parent. So it would hit when the child form closes and do your stuff there.

    advancedSearch.FormClosing += AdvancedSearch_FormClosing;
    advancedSearch.ShowDialog();
    

    private void AdvancedSearch_FormClosing(object sender, FormClosingEventArgs e)
        {
            var advanceSearch = sender as frmAdvancedSearch;
            if (advanceSearch.SelectedItem != null)
            {
                myColumnComboBox.Text = advanceSearch.SelectedItem.Name;
            }
        }
    

    Hope this helps.

提交回复
热议问题