Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have an application in vb.net that starts with a sub function do some things and decide if it shows itself or not. When it shows itself it does so by invoking dialog.ShowDialog().

When dialog.ShowDialog() returns, the application does some cleaning and ends.

I'd like to find a way to temporarily hide the dialog (send it to the system tray) without returning from the ShowDialog() function. However, as soon as I do a me.Hide() in the form's code, the form is effectively hidden, but the ShowDialog() function returns and the process is closed.

I understand this is the expected behavior. So my question is how can I get this effect? That is launch a dialog, that can be hidden, and block until the user really wants to quit the application.

like image 538
Mathieu Pagé Avatar asked Mar 11 '10 22:03

Mathieu Pagé


People also ask

What is the difference between show and ShowDialog?

Show() method shows a windows form in a non-modal state. ShowDialog() method shows a window in a modal state and stops execution of the calling context until a result is returned from the windows form open by the method.

Is a dialog a modal?

Definition: A modal dialog is a dialog that appears on top of the main content and moves the system into a special mode requiring user interaction. This dialog disables the main content until the user explicitly interacts with the modal dialog.

What is ShowDialog?

ShowDialog shows the window, disables all other windows in the application, and returns only when the window is closed. This type of window is known as a modal window. Modal windows are primarily used as dialog boxes.


2 Answers

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#

like image 193
John Knoeller Avatar answered Nov 14 '22 21:11

John Knoeller


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.

like image 27
Hans Passant Avatar answered Nov 14 '22 19:11

Hans Passant