Search code examples
c#winformsmdichild

ShowDialog property for MDI winforms


Question:

How do I display a MDI child form in a ShowDialog() format?

What I've tried:

private void Add()
        {

            ModuleAddPopUp map = new ModuleAddPopUp();
            map.StartPosition = FormStartPosition.CenterScreen;
            map.ShowDialog();          
        }

Doing the above, the form displays center screen as a pop-up, however I can drag the form outside the MDI when the MDI isn't maximized.

private void Add()
        {
            ModuleAddPopUp map = new ModuleAddPopUp();
            FormFunctions.OpenMdiDataForm(App.Program.GetMainMdiParent(), map);

        }

Doing the above, the form displays center screen, doesn't allow for the form to be dragged outside the MDI, but acts as a map.Show() , rather than a map.ShowDialog();


Solution

  • Add this code to your ModuleAddPopup class:

    protected override void WndProc(ref Message message)
    {
        const int WM_SYSCOMMAND = 0x0112;
        const int SC_MOVE = 0xF010;
        //SC_SIZE = 0XF000 if you also want to prevent them from resizing the form.
        //Add it to the 'if' condition.
        switch (message.Msg)
        {
            case WM_SYSCOMMAND:
                int command = message.WParam.ToInt32() & 0xfff0;
                if (command == SC_MOVE)
                    return;
                break;
        }
    
        base.WndProc(ref message);
    }
    

    This is native code wrapped in C# code, as seen in here. This, however, will prevent the user from moving the dialog form anywhere.

    Then, in your main form:

    private void Add()
    {
        ModuleAddPopUp map = new ModuleAddPopUp();
        map.StartPosition = FormStartPosition.CenterParent;
        map.ShowDialog();          
    }