Setting programmatically closereason

后端 未结 4 681
你的背包
你的背包 2021-02-19 10:25

I want to set the CloseReason of a form after I call This.Close() inside the form.

Usually, this forms is closed by itself calling This.Close(), but I want to ask the us

4条回答
  •  走了就别回头了
    2021-02-19 10:55

    The way I have started doing this is to set the DialogResult property of the form to different things based on what the user has clicked on the form.

    In your button click method:

    private void FillOrder_Click(object sender, EventArgs e)
    {
        this.DialogResult = DialogResult.OK;
        // this.Close() is called automatically when you set DialogResult
        // so the above line will close the form as well.
    }
    

    This way you can do the following in the FormClosing methods:

    private void Form_FormClosing(object sender, FormClosingEventArgs e)
    {
        switch (e.CloseReason)
        {
            case CloseReason.UserClosing:
                switch (this.DialogResult)
                {
                    case DialogResult.OK:
                        // User has clicked button.
                        break;
                    case DialogResult.Cancel:
                        // User has clicked X on form, show your yes/no/cancel box here.
    
                        // Set cancel here to prevent the closing.
                        //e.Cancel = true;
                        break;
                }
                break;
        }
    }
    

    As far as the CloseReason always being set to UserClosing, it is set to this value by any action that a user can initiate, can't remember exactly what but I'm pretty sure even a task manager force kill is user closing. However I can confirm the other enum values are set in various cases such as a shutdown/reboot while the app is still running. You can even stop windows shutting down by catching ALL close reasons in the switch and cancelling the close.

提交回复
热议问题