How to Create a Simple Calculator Application in Windows Forms

0

Learn how to create a basic calculator app and start your programming journey with Windows Forms.

When you’re learning to code, it can be helpful to gain experience by recreating apps that already exist. A common beginner app you can start with is a calculator.

You can create a desktop calculator application using a Windows Forms project in Visual Studio. In a Windows Forms application, you can click and drag UI elements onto a canvas to visualize your calculator design.

USE VIDEO OF THE DAY

You can then add code logic to the underlying C# files to determine what should happen when the user clicks a number, operator, clear or equals button.

How to Add UI Elements to Calculator

Start by creating a new Windows Form application in Visual Studio. Next, add UI elements to the canvas to create the calculator UI.

How to add number and operator buttons

Add buttons to represent numbers and operators (+, -, etc.) that the user will click on.

  1. Navigate to the canvas, which should be open by default. If not, click the .cs file for the form (for example Form1.cs). Click the drop-down menu and switch to design mode.
  2. In the toolbox, find a Button UI element. Click and drag a button onto the canvas.
  3. Highlight the button. In the properties window, replace each of the following button properties with its corresponding new value:
    Property New value
    Last name button1
    Cut 120, 120
    Text 1
  4. Add 19 more buttons to the canvas to represent other calculator numbers, operators, and functions.
  5. For each button, highlight it and change the text and name property in the properties window. Change the values ​​to match the button number or function.
    Button Property name Text property
    2 button2 2
    3 button3 3
    4 button4 4
    5 button5 5
    6 button6 6
    seven button7 seven
    8 button8 8
    9 button9 9
    0 button0 0
    Addition buttonAdd +
    Substraction Subtraction button
    Multiplication Multiplication button X
    Division ButtonDivision ÷
    Comma decimal button .
    Equal sign equals button =
    Right bracket buttonRightBracket )
    left support buttonLeftBracket (
    Clear clear button VS
    Delete Entry ClearEnter button THIS
  6. Rearrange the order of the buttons to replicate the appearance of a standard calculator. Keep all buttons the same size.
  7. You can also highlight certain buttons and change their color to one of your choice, using the Background color property in the properties window.
  8. For example, highlight add button. Go to the properties window and find the Background color property. Picking out Silver in the list of drop-down options. You can create operator buttons silverand the C and CE keys orange.


How to add the output result label

Add a text box UI element to represent the result that the calculator will display to the user.

  1. In the toolbox, drag a panel ui element on the Web.
  2. Highlight the panel and find the Background color property in the properties window. Change this to white. You can also resize and reposition the panel to make it look more like a calculator.
  3. In the toolbox, drag a TextBox UI element on the Web.
  4. Highlight the text box. In the properties window, replace the following properties with the new value:
    Property New value
    Last name textBoxOutput
    border style None
    Text 0
    Text alignment Right
    Enabled Fake
    Background color White
  5. Position the text box inside the panel.

How to add calculation logic

Add code to run the calculation logic when the user clicks the buttons.

  1. Open your .cs file for the form (for example, Form1.cs).
  2. Declare a variable called currentcalculation, at the top of the class. You can learn how to create classes in C# if you don’t know them.
    public partial class Form1 : Form
    {
    private string currentCalculation = "";

    public Form1()
    {
    InitializeComponent();
    }
    }

  3. Below the constructor, create a new function called button_Click(). This will run whenever the user clicks on a number button (0-9) or operator (+, -, X, ÷, etc.).
    private void button_Click(object sender, EventArgs e)
    {

    }

  4. One of the arguments passed to the button_Click() function is the object of the button on which the user clicks. Add the button object’s text property to the string calculation. As the user clicks the buttons, it will create a string for the calculation, such as “22+5-7”.
    private void button_Click(object sender, EventArgs e)
    {
    currentCalculation += (sender as Button).Text;


    textBoxOutput.Text = currentCalculation;
    }

  5. Return to the canvas. Highlight each button (except the C, CE, and Equal buttons) and navigate to the Events window. Find it Click on event, and select the button_Click() function. This will trigger the function to run when you click the button.


How to calculate the result and display it to the user

Create another function to calculate the final result when the user clicks on the equals button.

  1. Create a new function called button_Equals_Click(). First, you will need to format the string to replace the X and ÷ characters with * and /. Then use the Calculate() function to calculate the result. Display the result to the user.
    private void button_Equals_Click(object sender, EventArgs e)
    {
    string formattedCalculation = currentCalculation.ToString().Replace("X", "*").ToString().Replace("÷", "/");

    try
    {
    textBoxOutput.Text = new DataTable().Compute(formattedCalculation, null).ToString();
    currentCalculation = textBoxOutput.Text;
    }
    catch (Exception ex)
    {
    textBoxOutput.Text = "0";
    currentCalculation = "";
    }
    }

  2. Make sure to include the try-catch block around the Calculate() to capture all invalid entries, such as “123++7”. In this case, if the user enters an invalid calculation, the result will always return 0.
  3. The Calculate() function is part of System.Data namespace. Add the using statement to include it at the top of the class, if it’s not already there.
    using System.Data;
  4. Return to the canvas. Highlight the equals button and navigate to the Events window. Find it Click on event, and select the button_Equals_Click() function. This will trigger the function to run when you click the equals button.


How to clear the calculator

Add functionality for C (Clear) and CE (Clear Entry) buttons. The Clear will completely erase the current calculation. The Delete Entry will only erase the last number or operator entered.

  1. Create another function called button_Clear_Click(). This will run when the user clicks on the Clear button on the calculator. In the function, reset the calculation and the value in the results text box.
    private void button_Clear_Click(object sender, EventArgs e)
    {
    textBoxOutput.Text = "0";
    currentCalculation = "";
    }
  2. On the canvas, highlight Clear button and go to Events window.
  3. Find it Click on an event. Change the value to button_Clear_Click.
  4. Create another function called button_ClearEntry_Click(). This will run when the user clicks on the Delete Entry button on the calculator. In the function, delete the last character of the current calculation string.
    private void button_ClearEntry_Click(object sender, EventArgs e)
    {
    if (currentCalculation.Length > 0)
    {
    currentCalculation = currentCalculation.Remove(currentCalculation.Length - 1, 1);
    }


    textBoxOutput.Text = currentCalculation;
    }

  5. On the canvas, highlight Delete Entry button and go to Events window.
  6. Find it Click on an event. Change the value to button_ClearEntry_Click.


How to run the Calculator app

You can run the calculator in Visual Studio to test its functionality.

  1. Click the green play button at the top of the Visual Studio application.
  2. Click on the calculator buttons. The calculation will appear in the white space at the top of the calculator. By pressing the equals will replace it with the answer. The Clear and Delete Entry will also clear the calculation or entry.

Creating Desktop Applications Using Windows Forms

You can create a desktop calculator application using a Windows Forms project in Visual Studio. Use the canvas and toolbox to drag and drop UI elements to create the calculator design. Add your code logic and functionality in the C# code behind the files.

A calculator is just one of many simple beginner apps you can create while learning to code. Other beginner apps you can create include converters, file managers, dice games, or flag generators. You can create them from scratch using a Windows Forms application.

Share.

About Author

Comments are closed.