C# Winforms center and close Form(2 methods)

Lionsure 2020-08-14 Original by the website

The Subform is displayed in the upper left corner of main Form by default in Winforms. When the Subform is small, it looks unsightly and unconventional, or the center of Form is both beautiful and conforms to the habits of most users. How to center the Form? See below to share.

There are several ways in Winforms to close the Form. Close is the most common and simplest way, but it cannot end the unfinished process. Therefore, if you close the window and require the end of all processes of program, you have to find another way. As for the method used, share in the article introducing C# Winforms to close the Form.

 

I. C# Winforms center Form

There are two ways to center a Form in Winforms, one is to set with code, and the other is to set its properties, respectively as follows:

 

1. Center Form with code

this.StartPosition = FormStartPosition.CenterParent;

 

2. Set the properties of form to center it

1) Select the Form, open the small "Properties" dialog box on the right, find StartPosition, and select its value as CenterParent(centered relative to the parent Form), as shown in Figure 1:

C# Winforms center Form

Figure 1

2) After saving, the generated window is centered.

 

 

II. C# Winforms close Form

Method 1: Close() method

The Close() method can only close the Form, and cannot end the process that has not been completed(For example, a task is started before the Form is closed, and the task has not been completed. After the window is closed, it will continue to be executed until the execution is completed), code show as below:

this.Dispose();

this.Close();//this can also be replaced by the name of Form

 

Method 2: Environment.Exit(int exitCode) method

The Environment.Exit() method not only closes the Form, but also forcibly terminates the process that has not yet been executed. For example, when the Form is closed, a process is downloading a file, the process is also forced to end, the code is as follows:

Environment.Exit(0);

 

exitCode is the exit code provided to the operating system, and 0 indicates that the processing has completed successfully.