Search code examples
c#.netwinformsdialogtoplevel

Top level window in WinForms


There are a lot of questions around about this for WinForms but I haven't seen one that mentions the following scenario.

I have three forms:

(X) Main  
(Y) Basket for drag and drop that needs to be on top  
(Z) Some other dialog form  

X is the main form running the message loop.
X holds a reference to Y and calls it's Show() method on load.
X then calls Z.ShowDialog(Z).

Now Y is no longer accessible until Z is closed.

I can somewhat understand why (not really). Is there a way to keep Y floating since the end user needs to interact with it independently of any other application forms.


Solution

  • If you want to show a window using ShowDialog but you don't want it block other windows other than main form, you can open other windows in separate threads. For example:

    private void ShowY_Click(object sender, EventArgs e)
    {
        //It doesn't block any form in main UI thread
        //If you also need it to be always on top, set y.TopMost=true;
    
        Task.Run(() =>
        {
            var y = new YForm();
            y.TopMost = true;
            y.ShowDialog();
        });
    }
    
    private void ShowZ_Click(object sender, EventArgs e)
    {
        //It only blocks the forms of main UI thread
    
        var z = new ZForm();
        z.ShowDialog();
    }