How to hide a modal dialog without returning from .ShowDialog?

帅比萌擦擦* 提交于 2019-12-01 04:23:19

You cannot make this work, ShowDialog() will always return when the form is hidden. The trick is to use a regular form and a normal call to Application.Run() but to prevent it from becoming visible immediately. Paste this code into your form class:

Protected Overrides Sub SetVisibleCore(ByVal value As Boolean)
    If Not IsHandleCreated Then
        CreateHandle()
        value = false
    End If
    MyBase.SetVisibleCore(value)
End Sub

Beware that your Load event handler won't run until the form actually becomes visible so be sure to do any initialization in the Sub New constructor.

John Knoeller

If you hide the dialog, you will return from ShowDialog(). Forget about trying to change that, you can't.

You might be able to minimize the dialog.

form1.WindowState = FormWindowState.Minimized;

Or you can position it off screen.

form.Left = -16384;

Or you can make it transparent Modifying opacity of any window from C#

Another workaround is to change the modeled form's Opacity property to 0 to make it fully transparent.

private void MyModalForm_Load(object sender, EventArgs e)
{
    bool isShowing = true;
    //Do your thing.
    if(!isShowing) this.Opacity = 0.0;
    else this.Opacity = 1.0;
}

you may use a flag.

  1. Add a flag to your form : bool done = false;
  2. set done = true when it is complete (in FormClosed event).
  3. check for flag in caller function (is it done ?)

    bool stilInMyFrm = false;
    MyFrm myFrm = new myFrm();
    
    try
    {
        stilInMyFrm = true;
        myFrm.ShowDialog();
        while (!myFrm.done)
            Application.DoEvents();
    }
    finally
    {
        stilInMyFrm = false;
        cleanup();
    }
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!