How to Build a Simple Calculator App in Windows Forms

Learn how to create a basic calculator app and begin your programming journey with Windows Forms.
When learning how to code, it can be useful to gain experience by re-creating apps that already exist. One common beginner app that you can 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 the design of your calculator.
You can then add code logic to the underlying C# files to determine what should happen when the user clicks on a number, operator, clear, or equals button.
How to Add UI Elements to the Calculator
Start by creating a new Windows Form Application in Visual Studio. Then, add UI elements to the canvas to create the calculator’s user interface.
How to Add the Number and Operator Buttons
Add buttons to represent the numbers and operators (+, -, etc.) that the user will click on.
- Navigate to the canvas, which should be open by default. If it isn’t, click on the .cs file for the form (e.g. Form1.cs). Click the dropdown and switch to design mode.
- In the Toolbox, search for a Button UI element. Click and drag a button onto the canvas.
- Highlight the button. In the properties window, change each of the following button properties to its corresponding new value:
Property New Value Name button1 Size 120, 120 Text 1 - Add 19 more buttons to the canvas to represent the other numbers, operators, and functions of the calculator.
- For each button, highlight the button and change the text and name property in the property window. Change the values to match the button’s number or function.
Button Name Property Text Property 2 button2 2 3 button3 3 4 button4 4 5 button5 5 6 button6 6 7 button7 7 8 button8 8 9 button9 9 0 button0 0 Addition buttonAddition + Subtraction buttonSubtraction – Multiplication buttonMultiplication X Division buttonDivision ÷ Decimal Point buttonDecimal . Equals Sign buttonEquals = Right Bracket buttonRightBracket ) Left Bracket buttonLeftBracket ( Clear buttonClear C Clear Entry buttonClearEntry CE - Rearrange the order of the buttons to replicate the look of a standard calculator. Keep all the buttons the same size.
- You can also highlight some buttons and change their color to one of your choice, using the BackColor property in the properties window.
- For example, highlight the addition button. Go into the properties window and find the BackColor property. Choose Silver from the list of options in the dropdown. You can make operator buttons silver, and the C and CE buttons orange.
How to Add the Output Result Label
Add a textbox UI element to represent the result that the calculator will display to the user.
- In the Toolbox, drag a Panel UI element onto the canvas.
- Highlight the panel, and find the BackColor property in the properties window. Change this to white. You can also re-size and re-position the panel to make it look more like a calculator.
- In the Toolbox, drag a TextBox UI element onto the canvas.
- Highlight the textbox. In the properties window, change the following properties to the new value:
Property New Value name textBoxOutput BorderStyle None Text 0 TextAlign Right Enabled False BackColor White - Position the textbox inside the panel.
How to Add the Calculation Logic
Add code to execute the calculation logic when the user clicks on the buttons.
- Open your .cs file for the form (for example, Form1.cs).
- Declare a variable called currentCalculation, at the top of the class. You can learn how to create classes in C# if you’re not familiar with them.
public partial class Form1 : Form
{
private string currentCalculation = "";public Form1()
{
InitializeComponent();
}
} - Underneath the constructor, create a new function called button_Click(). This will execute every time the user clicks on a number (0-9) or operator (+, -, X, ÷, etc.) button.
private void button_Click(object sender, EventArgs e)
{}
- One of the arguments passed to the button_Click() function is the object of the button the user clicks on. Add the text property of the button object to the string calculation. As the user clicks on buttons, this will build 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;
} - Go back to the canvas. Highlight each button (excluding the C, CE, and equals buttons) and navigate to the Events window. Find the Click event, and select the button_Click() function. This will trigger the function to execute 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.
- 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 Compute() function to calculate the result. Display 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 = "";
}
} - Make sure you include the try-catch block around the Compute() function to capture any invalid inputs, such as “123++7”. In this case, if the user enters an invalid calculation, the result will always return 0.
- The Compute() function is part of the System.Data namespace. Add the using statement to include it at the top of the class, if it is not already there.
using System.Data;
- Go back to the canvas. Highlight the equals button, and navigate to the Events window. Find the Click event, and select the button_Equals_Click() function. This will trigger the function to execute when you click the equals button.
How to Clear the Calculator
Add the functionality for the C (Clear) and CE (Clear Entry) buttons. The Clear button will completely erase the current calculation. The Clear Entry button will only erase the last entered number or operator.
- Create another function called button_Clear_Click(). This will execute when the user clicks on the Clear button on the calculator. Inside the function, reset the calculation and the value inside the results textbox.
private void button_Clear_Click(object sender, EventArgs e)
{
textBoxOutput.Text = "0";
currentCalculation = "";
} - On the canvas, highlight the Clear button, and navigate to the Events Window.
- Find the Click event. Change the value to button_Clear_Click.
- Create another function called button_ClearEntry_Click(). This will execute when the user clicks on the Clear 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;
} - On the canvas, highlight the Clear Entry button, and navigate to the Events Window.
- 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.
- Click on the green play button at the top of the Visual Studio application.
- Click on the buttons of the calculator. The calculation will show in the white space at the top of the calculator. Pressing the equals button will replace it with the answer. The Clear and Clear Entry buttons will also clear the calculation or entry.
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 make up the design of the calculator. Add your code logic and functionality in the C# code behind files.
A calculator is just one of many simple beginner apps that you can make while learning to code. Other beginner apps you can create include converters, file managers, dice games, or flag generators. You can create these from scratch using a Windows Forms application.