Home > Software design >  How do I open another window (Form) when a button is pressed?
How do I open another window (Form) when a button is pressed?

Time:12-26

Complete C# beginner here, just wondering how to open an existing form from within the current form, and close the first one. I have literally no code yet so any help is much appreciated

I had a bit of a mess around, of course not knowing anything. Something like this is about all I tried just going off of intellisense prompts:

Application.Run(Terry2);

It obviously didn't work. Here was the error

Error CS0119 'Window2' is a type, which is not valid in the given context. I have no idea where to start so thanks in advance for the help. I am using Visual Studio 2022.

CodePudding user response:

Actually there are plenty of examples for this code on the internet, first you should create both of your forms and then just create an instance of your form2 in form1 under the event of your form1's button and call it's Show() method.

private void button1_Click(object sender, EventArgs e)
{
    Form2 f2 = new Form2();
    f2.ShowDialog(); // Shows Form2 you can also use f2.Show() 
}

Here is a step by step explenation of the process that you should follow. I recommend you to watch some fundamental c# programming tutorials as well. Click Here

CodePudding user response:

If you've used windows for some time, you've noticed that there are two types of Dialog Boxes (forms): Modal and Modeless Dialog Boxes

  • Modal dialog boxes: while this one is being shown, you cannot use the other dialog boxes of the application; you'll have to finish this one before you can continue using your application. Example: File Open dialog box.
  • Modeless Dialog Box. A kind of dialog box that gives some extra information next to the other dialog box of your application. While this one is being shown, you can switch back to your original dialog box and enter some input.

How to show a modal dialog box

For this, you use Form.ShowDialog

In your form:

private DialogResult AskFileName()
{
    using (Form myForm = new SaveFileDialog();
    {
        // Before showing the dialog box, set some properties:
        myForm.Title = "Save file";
        myForm.FileName = this.DefaultFileName;
        myForm.ValidateNames = true;
        ...

        // show the file save dialog, and wait until operator closes the dialog box
        DialogResult dlgResult = myForm.ShowDialog(this);
        // if here, you know the operator closed the dialog box;
        return dlgResult;
    }
}

private void SaveFile()
{
    DialogResult dlgResult = this.AskFileName();
    switch (dglResult)
    {
        case DialogResult.Ok:
            // File is saved:
            this.HandleFileSaved();
            break;
        case DialogResult.Cancel();
            // operator pressed cancel
            this.ReportFileNotSaved();
            break;
        ...
    }
}

A form is disposable, hence you should use the using statement. After creation of the form you have time to set the properties. The form is shown using ShowDialog. While this dialog box is shown, your form can't get the focus. After the operator closes the dialog box, your form gets the focus again. The return value of ShowDialog indicates the result.

If you want to save the file as a result of the operator selecting the menu item "file save", or pressing the button "Save", do the following:

private void OnMenuItemFileSave_Clicked(object sender, ...)
{
    this.SaveFile();
}
private void OnButtonSave_Clicked(object sender, ...
{
    this.SaveFile();
}  

How to show a modeless Dialog Box

A modeless dialog box is shown using Form.Show. After you call this, your dialog box can get the focus. Therefore you'll have to remember that the form is being shown.

class MyModelessDialogBox : Form {...}

class MyForm : Form
{
    private MyModelessDialogBox {get; set;} = null;

    private void ShowMyModelessDialogBox()
    {
        if (MyModelessDialogBox != null)
        {
            // Dialog box already shown, TODO: report to operator?
            ...
            return;
        }
        else
        {
            // Dialog box not shown yet; create it and show it
            this.MyModelessDialogBox =  new MyModelessDialogBox();
            // if needed, before showing set some properties

            // make sure you get notified if the dialog box is closed
            this.MyModelessDialogBox.FormClosed  = new FormClosedEventHandler(this.MyModelessDialogBoxClosed);

            // show the dialog box:
            this.MyModelessDialogBox.Show(this);   // I am the owner / parent window
        }

        // when the modeless dialog box is closed, you get notified:
        void MyModelessDialogBoxClosed(object sender, FormClosedEventArgs e)
        {
            // if needed, inspect e.CloseReason
            // if needed, handle the DialogResult
            // finally: not my form anymore. The form should disposes itself:
            this.MyModelessDialogBox = null;
        }
    }

} }

Before closing your form you should check if the dialog box is being shown, and close:

private void OnFormClosing(object sender, FormClosingEventArgs e)
{
    if (this.MyModelessDialogBox != null)
    {
        // the modeless dialog box is being shown. Order it to close itself:
        this.MyModelessDialogBox.Close();
        // this will lead to MyModelessDialogBoxClosed
    }
}

Sometimes you have a dialog box that refuses to close, for instance because the dialog box warns the operator and he clicks cancel. In that case, you should not Close the dialog box directly, but add a method to ask the dialog box nicely.

In the dialog box:

bool RequestToClose()
{
    bool allowedToClose = this.AskOperatorIfCloseAllowed();
    if (allowedToClose)
    {
        // close this dialog box.
        this.Close();
        // the owner of the dialog box will be notified via MyModelessDialogBoxClosed
    }
    return allowedToClose;
}
  • Related