How to close form

后端 未结 8 2164
南旧
南旧 2021-02-18 23:54

Ok, so a Windows Forms class, WindowSettings, and the form has a \"Cancel\"-button. When the user clicks the button, the dialog DialogSettingsCancel will pop-up up and ask the u

相关标签:
8条回答
  • 2021-02-19 00:17

    You need the actual instance of the WindowSettings that's open, not a new one.

    Currently, you are creating a new instance of WindowSettings and calling Close on that. That doesn't do anything because that new instance never has been shown.

    Instead, when showing DialogSettingsCancel set the current instance of WindowSettings as the parent.

    Something like this:

    In WindowSettings:

    private void showDialogSettings_Click(object sender, EventArgs e)
    {
        var dialogSettingsCancel = new DialogSettingsCancel();
        dialogSettingsCancel.OwningWindowSettings = this;
        dialogSettingsCancel.Show();
    }
    

    In DialogSettingsCancel:

    public WindowSettings OwningWindowSettings { get; set; }
    
    private void button1_Click(object sender, EventArgs e)
    {
        this.Close();
        if(OwningWindowSettings != null)
            OwningWindowSettings.Close();
    }
    

    This approach takes into account, that a DialogSettingsCancel could potentially be opened without a WindowsSettings as parent.

    If the two are always connected, you should instead use a constructor parameter:

    In WindowSettings:

    private void showDialogSettings_Click(object sender, EventArgs e)
    {
        var dialogSettingsCancel = new DialogSettingsCancel(this);
        dialogSettingsCancel.Show();
    }
    

    In DialogSettingsCancel:

    WindowSettings _owningWindowSettings;
    
    public DialogSettingsCancel(WindowSettings owningWindowSettings)
    {
        if(owningWindowSettings == null)
            throw new ArgumentNullException("owningWindowSettings");
    
        _owningWindowSettings = owningWindowSettings;
    }
    
    private void button1_Click(object sender, EventArgs e)
    {
        this.Close();
        _owningWindowSettings.Close();
    }
    
    0 讨论(0)
  • 2021-02-19 00:18

    You can also close the application:

    Application.Exit();
    

    It will end the processes.

    0 讨论(0)
提交回复
热议问题