Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form.Close() is closing other form (dialog) also

Tags:

c#

forms

winforms

I have a simple winforms application. The application starts with MainForm which is hidden all the time. MainForm opens another form called Notification (.Show) which closes after 10 seconds. So if the MainForm opens a dialog form (.ShowDialog) while Notification is still open, the open dialog also closes if Notification hits 10 seconds and closes.

The Notification form as well as the dialog form have TopMost = True

An example:

Short example: The OtherDialogForm closes also even if my application only does this:

public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
        new Notification("Title", "Content").Show(); // closes itself after 10 seconds
        new OtherDialogForm().ShowDialog(); // being closed by form above (not wanted)
    }
}

Longer example: MainForm.cs

public partial class MainForm : Form
{
    protected override void SetVisibleCore(bool value)
    {
        base.SetVisibleCore(false);
    }

    public MainForm() 
    {
        CreateNotification();
    }

    public void CreateNotification()
    {
        new Notification.Show();
    }

    // triggered while Notification (from above) is still open
    private async void TriggeredByHotkey()
    {
        using (OtherDialogForm dialog = new OtherDialogForm())
        {
            dialog.ShowDialog();
            // if DialogResult == ...
        }
    }
}

Notification.cs

public partial class Notification : Form
{
    Timer timer;

    public Notification()
    {
        // sets timer tick to 10 seconds,
        // then calls void with this.Close()
    }

    // not sure if I really need this, but the problem is still there without
    protected override CreateParams CreateParams
    {
        get
        {
            var cp = base.CreateParams;
            cp.ExStyle |= 8;  // Turn on WS_EX_TOPMOST
            return cp;
        }
    }
}

I have really no idea why the dialog closes together with Notification.

like image 644
Vaza Avatar asked Sep 03 '25 04:09

Vaza


1 Answers

You can hide the Notification form instead of closing it, since is just a notification you do not really need to close it, you can keep it in the background and show it when is needed. From the msdn: https://msdn.microsoft.com/en-us/library/c7ykbedk(v=vs.110).aspx

This version of the ShowDialog method does not specify a form or control as its owner. When this version is called, the currently active window is made the owner of the dialog box. If you want to specify a specific owner, use the other version of this method.

So if you are using ShowDialog and the Notification form becomes the parent of the other dialig form, they both will be closed at closing Notification form

like image 180
meJustAndrew Avatar answered Sep 04 '25 23:09

meJustAndrew