How to Create a Simple Calculator App in Windows Forms – MUO – MakeUseOf | Hot Mobile Press

Learn how to create a simple calculator app and start your coding journey with Windows Forms.

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

You can create a desktop calculator app 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’s design.

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

How to add UI elements to the calculator

First, create a new Windows Form application in Visual Studio. Then add UI elements to the canvas to create the calculator UI.

How to add the number and operator buttons

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

  1. Navigate to the canvas, which should be open by default. If not, click .cs File for the form (ex Form1.cs). Click on the drop down menu and switch to design mode.

  2. In the toolbox, look for a button UI element. Click a button and drag it onto the canvas.
  3. Highlight the button. In the Properties window, change each of the following button properties to the appropriate new value:
    Property New value
    Surname button 1
    size 120, 120
    text 1

  4. Add 19 more buttons to the canvas to represent the calculator’s other numbers, operators, and functions.
  5. For each button, highlight the button and change the Text and Name property in the Properties window. Change the values ​​according to the number or function of the button.
    button name property Text property
    2 button2 2
    3 button3 3
    4 button4 4
    5 button5 5
    6 button6 6
    7 button7 7
    8th button8 8th
    9 button9 9
    0 key0 0
    additive button addition +
    subtraction Subtraction button
    multiplication Multiplication button X
    division Division button ÷
    comma buttonDecimal .
    equal sign Equals button =
    right parenthesis buttonRightBracket )
    left parenthesis buttonLeftBracket (
    Clear Delete button C
    Delete Entry Delete entry button CE
  6. Rearrange the order of the buttons to replicate the look of a standard calculator. Keep all keys the same size.

  7. You can also highlight some buttons and change their color to a color of your choice using background color property in the properties window.
  8. For example, mark the modifier button. Go to the properties window and look for the background color Property. Choose Silver from the list of options in the drop-down list. You can create control buttons Silver-and 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 show to the user.

  1. In the toolbox, drag a Panel UI element on the canvas.
  2. Highlight the control panel and locate 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 canvas.
  4. Highlight the text box. In the Properties window, change the following properties to the new value:
    Property New value
    Surname textBoxOutput
    BorderStyle none
    text 0
    text alignment Right
    Allowed NOT CORRECT
    background color White
  5. Position the text box inside the panel.

How to add the calculation logic

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

  1. open yours .cs File for the form (e.g. Form1.cs).
  2. Declare a variable called current calculation, at the top of the class. You can learn how to create classes in C# if you are not familiar with it.
    public partial class Form1 : Form
    {
    private string currentCalculation = "";

    public Form1()
    {
    InitializeComponent();
    }
    }

  3. Under the constructor, create a new function named button_Click(). This is run every time the user clicks on a number (0-9) or an 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 that the user clicks. Add the button object’s text property to the string calculation. When the user clicks buttons, it creates a string for the calculation, e.g. “22+5-7”.
    private void button_Click(object sender, EventArgs e)
    {
    currentCalculation += (sender as Button).Text;


    textBoxOutput.Text = currentCalculation;
    }

  5. Go back to the canvas. Highlight each button (except for the C, CE, and Equality buttons) and navigate to events window. Find the click Event and select that 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 the equals button.

  1. Create a new function called button_Equals_Click(). First you need to format the string to replace the X and ÷ sign with * and /. Then use the To calculate() Function to calculate the result. Show the result back 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. Be sure to include the try-catch block around the To calculate() Function to capture invalid input like “123++7”. In this case, if the user enters an invalid calculation, the result always returns 0.
  3. That To calculate() Function is part of system data namespace. Add the using statement to include at the top of the class if it’s not already there.
    using System.Data;
  4. Go back to the canvas. Highlight the same button and navigate to events window. Find the click Event and select that button_Equals_Click() Function. This will trigger the function to run when you click the equals button.


How to delete the calculator

Add functionality for C (Clear) and CE (Clear Entry) buttons. That Clear clears the current calculation completely. That Delete Entry deletes only the last entered number or operator.

  1. Create another function called button_Clear_Click(). This is executed when the user clicks the Clear button on the calculator. Within the function, reset the calculation and the value in the result text box.
    private void button_Clear_Click(object sender, EventArgs e)
    {
    textBoxOutput.Text = "0";
    currentCalculation = "";
    }
  2. On the canvas, mark the Clear button and navigate to events window.
  3. Find the click Event. Change the value to button_Clear_Click.

  4. Create another function called button_ClearEntry_Click(). This is executed when the user clicks the Delete Entry button on the calculator. Inside the function, remove the last character from 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, mark the Delete Entry button and navigate to events window.
  6. Find the click Event. Change the value to button_ClearEntry_Click.


How to run the calculator application

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 is shown in the white area at the top of the calculator. pressing the same button will replace it with the answer. That Clear and Delete Entry Buttons also clear the calculation or input.

Creating desktop applications using Windows Forms

You can create a desktop calculator app 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 C# code behind files.

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

Leave a Comment