MFC and .NET Explorations

08 October 2004

Windows Forms: how to make a form behave like a modeless dialog?

Define a class deriving from Form. Declare it within the form that will be its parent:

          // Site Query window (modeless)

          private SiteQuery siteQuery = null;

When a button of the parent form toolbar is clicked, instantiate, show and activate the form:

          private void siteToolBar_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)

          {

                switch(siteToolBar.Buttons.IndexOf(e.Button))

                {

                      case 0: // Open Site

                            // Check SiteQuery windows exists

                           

                            if (siteQuery == null)

                            {

                                  siteQuery = new SiteQuery();

                            }

 

                            if (!siteQuery.Visible)

                                  siteQuery.Show();

                            siteQuery.Activate();

 

                            break;

 

By default when a form is closed, Form.Dispose() is called which then makes it impossible to call the Show() method. To avoid this, handle the Closing event:

          private void SiteQuery_Closing(object sender, System.ComponentModel.CancelEventArgs e)

          {

                e.Cancel = true;

               

                // Hide the form instead of closing it

                this.Hide();

          }