In C# programming development in order to program visualization and user operation more convenient, usually use winform user interaction interface development.

C#, you may ask, is not game development, why use interactive interface design? In fact, C# in addition to game development, it and Java, C++ languages, can do a lot of things of course!

Today, the big bad Wolf will use C# to do a winform calculator, so as to achieve the simple development of the interactive interface.

The development of winForm calculator needs to be carried out in the development environment of the form application, and can be in the. Cs design interface for the simple design layout of the calculator,

Visual Studio is very convenient in this point, we can design interface toolbox directly to the layout of the interface.

At the same time, after clicking the control, you can set the text content, background color, foreground color, font size and other properties displayed by the control.

It is important to note that each control in WinForm is associated with an event that can be triggered when the control is clicked. This function has the same name as the control and can be set in the control’s property bar.

Then double-click the control to automatically generate the following control function in the WinForm interface class:

Winform calculator in order to realize the basic controls, empty, including digital, decimal, addition, subtraction, multiplication, and division is equal to, such as text box control, at the same time friend can also be designed according to the demand and add other features, this is the design of the Wolf “nokia brand screen showing a smart calculator” interactive interface, for reference only, huh.

After the interactive interface design is completed, after that is the writing operation of the control functions and some other functions,

The first thing to do is to write out the functions for each control. These functions can be automatically generated by double-clicking the control directly in Visual Studio. This point is very convenient, can greatly save our development of the function programming time.

Then we need to define some variables to receive the content sent when the corresponding control is triggered. These variables can receive numbers, operators, decimal points, results, and other information when the calculator is used:

		private string strOutput = "";  // Define the output
        private double INumFormer = 0;  // Define the first number of inputs
        private double INumTemp = 0;    // Define the second number of inputs
        private double IResult = 0;     // Define the result
        private string cOperation;    // Define the operator
        private bool DotCliked = false;    // Define Boolean type judgment decimal point
        double lastPrecisionNum = 1;    // Define the precision of the last digit of the decimal point as 1
Copy the code

Empty function

This function is used to clear all input and return to the original interface for the user to enter the second time. The cleanup function needs to be written under the function associated with the control. The idea behind this function is to simply place all the previously defined receiver variables at their initial values. The specific code is as follows:

 // Empty button trigger function
    private void button_ce_Click(object sender, EventArgs e)
    {
        // Empty numeric variables
        INumFormer = 0;
        INumTemp = 0;
        IResult = 0;
        strOutput = "";
        cOperation = "";
        DotCliked = false;
        lastPrecisionNum = 1;
        txtOutPut.Text = "Why clean the screen again? You don't know how to count?";
    }
Copy the code

The decimal point button clicks the function

The point button click function is used to distinguish integer data from floating point data when the user performs a double operation by clicking the decimal point. Writing ideas for the first output content of the string after the decimal point, and then display in the text box, because we will judge the decimal point of the initial value of the DotCliked variable set to false, so after processing, to set the value of DotCliked to true, remind the system at this time of decimal calculation. The specific function code is as follows:

   // The decimal point button clicks the function
   private void button_dot_Click(object sender, EventArgs e)
    {
        if(! DotCliked) { strOutput +=".";
            txtOutPut.Text = strOutput;
            DotCliked = true; }}Copy the code

Centralized handling of button triggering event functions

This function is a function of our own definition, and is not automatically generate a control function types, the role of this function when receiving information triggered when the user clicks the button, and the decimal judgment, if the user typed value is a decimal, is the input data after the decimal point input data (click) ward a, said after the decimal point, And add the INumTemp data to get the decimal input. If it is not a decimal, it is worth noting that you should multiply the previously entered data by 10 and move it forward one bit.

At the same time give you a small suggestion, in order to judge whether the data overflow, in the judgement statements can add an exception thrown by the judge, so that when abnormal errors not cause the program can’t run, but send a wrong abnormal warning, so that it will be very convenient to know the problem of the program. This is a common practice in many programming situations, where exception throwing can prevent a program from failing.

The function implementation code is as follows:

 // Handle button trigger events centrally
        private void Numbers_Click(object sender, EventArgs e)
        {
            string strClickNum = ((Button)sender).Text;     // Get the text of the button control
            try
            {
                // Determine if the decimal type is clicked
                if (DotCliked)
                {
                    lastPrecisionNum *= 0.1;

                    // Get the decimal value and determine if there is an exception overflow
                    checked
                    {
                        INumTemp = INumTemp + long.Parse(strClickNum) * lastPrecisionNum;  // Convert the retrieved button string to long}}else
                {
                    checked
                    {
                        INumTemp = INumTemp * 10 + long.Parse(strClickNum);
                    }
                }
                txtOutPut.Text += INumTemp.ToString();
                strOutput += strClickNum;
                txtOutPut.Text = strOutput;
            }
            catch (Exception)
            {
                MessageBox.Show("Data overflow"); }}Copy the code

Operator button click event function

This function, like the centralized handling of the trigger button function, is our own defined function, the function is to receive the addition, subtraction, multiplication, division and other controls as they type operations, the writing idea of this function is that when the input operator, indicating that the last data has been entered.

In this case, we need to assign the value of INumTemp to the INumFormer to indicate that this is the first data we type, and then assign the value of INumTemp to 0 to facilitate the input of the second value. At the same time, the variable that defines the output will continue to increase on the original basis, and output the information through the text output box.

After that, the decimal point judgment variable and the decimal number variable are assigned to the initial value, which is convenient for two data inputs. The specific function implementation code is as follows:

 // operator button click event
        private void Opraters_Click(object sender, EventArgs e)
        {
            string strClickop = ((Button)sender).Text;  // Get the button value
            cOperation = strClickop;
            INumFormer = INumTemp;
            INumTemp = 0;
            strOutput += cOperation.ToString();
            txtOutPut.Text = strOutput;
            DotCliked = false;
            lastPrecisionNum = 1;
        }
Copy the code

The equal button triggers the event function

As the name implies, the function is to output the result typed, and the function is automatically generated when double clicking the equal sign control, we do not need to define ourselves, when we click the equal sign button will trigger the function.

The idea behind the equal button trigger function is to use the switch statement to determine the type of operator you type, and then to type the values INumFormer and INumTemp for the first and second time depending on which operator you type. Perform the corresponding addition, subtraction, multiplication and division, assign the result to IResult, and print the result through the text output box.

There are two ways to do this: One is to retype two numbers for operation, which requires that all the variables originally defined should be given initial values after the result is output. The other is to continue to click the operator for serial operation after the operation result is output, which requires that the operation result be assigned to INumFormer and INumTemp. The purpose is to store the results of the operation and continue the operation. Then assign initial values to all of the previously defined variables. The specific implementation code of the equal sign button trigger function is as follows:

// The equal button triggers the function
private void button_enter_Click(object sender, EventArgs e)
{
    try
    {
        switch (cOperation)
        {
            case "+":
                {
                    checked     // the chexked keyword checks for abnormal overflow
                    {
                        IResult = INumFormer + INumTemp;
                    }
                    break;
                }
            case "-":
                {
                    checked     // the chexked keyword checks for abnormal overflow
                    {
                        IResult = INumFormer - INumTemp;
                    }
                    break;
                }
            case "*":
                {
                    checked     // the chexked keyword checks for abnormal overflow
                    {
                        IResult = INumFormer * INumTemp;
                    }
                    break;
                }
            case "/":
                {
                    checked     // the chexked keyword checks for abnormal overflow
                    {
                        IResult = INumFormer / INumTemp;
                    }
                    break;
                }
            case "x2":
                {
                    checked     // the chexked keyword checks for abnormal overflow
                    {
                        IResult = INumFormer * INumFormer;
                    }
                    break;
                }
            case "x3":
                {
                    checked     // the chexked keyword checks for abnormal overflow
                    {
                        IResult = INumFormer * INumFormer * INumFormer;
                    }
                    break;
                }
        }
    }
    catch(Exception)
    {
        // Set the error overflow information dialog box
        MessageBox.Show("Calculation error overflow!");
        throw;
    }
    txtOutPut.Text = IResult.ToString();
    txtOutPut.Text += "Have you guessed the cameo file? ᴗ• Danjun.";
    strOutput = IResult.ToString();
    INumFormer = IResult;
    INumTemp = IResult;
    IResult = 0;
    cOperation = "";
    DotCliked = false;
    lastPrecisionNum = 1;
}
Copy the code

Interface control type setting function

The last and most critical step is to type controls in the functions of the user interface. This function is automatically generated when we create the interface. Here we need to use the EventHandler class to call Numbers_Click and Opraters_Click, respectively. This is so that we can respond when we click through the control, so that we do not do invalid operations when we click on the control. The concrete implementation of this function is as follows:

 public CaleForm()
    {
        InitializeComponent();
        EventHandler en = new EventHandler(Numbers_Click);
        button_num0.Click += en;
        button_num1.Click += en;
        button_num2.Click += en;
        button_num3.Click += en;
        button_num4.Click += en;
        button_num5.Click += en;
        button_num6.Click += en;
        button_num7.Click += en;
        button_num8.Click += en;
        button_num9.Click += en;

        EventHandler en2 = new EventHandler(Opraters_Click);
        button_add.Click += en2;    / / add
        button_sub.Click += en2;    / /
        button_mul.Click += en2;    / / by
        button_div.Click += en2;    / / in addition to
        button_square.Click += en2;    / / square
        button_cube.Click += en2;    / / cubic
    }
Copy the code

After these functions are basically completed, a simple Winform calculator is completed. We compile and run it directly in the form. At the same time, we can also add other operations according to different needs, such as square, cubic, square root and other operations.