Как написать калькулятор на c windows forms

Программируем калькулятор Windows Forms на языке C#: подробный разбор кода, возможность скачать исходник, описание алгоритма создания.

Некогда мы уже создавали подобный калькулятор, но он был довольно простенький и не имел общего TextBox’a для всех чисел.

В данной статье же мы создадим более усовершенствованный калькулятор Windows Forms.Итак, выглядеть у нас он будет вот так:

Калькулятор Windows Forms на языке C#

Здесь у нас 19 кнопок Button, 1 Textbox и ещё 1 пустой Label (на рисунке он выделен). Применение его будет описано ниже.

Итак, создаём такую или похожую форму. Мы увеличили ширину TextBox’a, используя MultiLine:

Калькулятор Windows Forms на языке C#

Также в Свойствах мы увеличили размер шрифта в TextBox’e и Label’e до 12 пт.

Калькулятор Windows Forms на языке C#

Теперь делаем так, чтобы при нажатии на цифровые кнопки, в TextBox’e появлялась соответствующая цифра.

Для этого дважды кликаем на кнопке «0» и в открывшемся коде пишем:

private void button17_Click(object sender, EventArgs e)

        {

            textBox1.Text = textBox1.Text + 0;

        }

Проверяем, несколько раз нажав на кнопку «0» у нас в форме.

Калькулятор Windows Forms на языке C#

Работает. Делаем то же самое с остальными цифровыми кнопками:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

private void button13_Click(object sender, EventArgs e)

        {

            textBox1.Text = textBox1.Text + 1;

        }

        private void button14_Click(object sender, EventArgs e)

        {

            textBox1.Text = textBox1.Text + 2;

        }

        private void button15_Click(object sender, EventArgs e)

        {

            textBox1.Text = textBox1.Text + 3;

        }

        private void button9_Click(object sender, EventArgs e)

        {

            textBox1.Text = textBox1.Text + 4;

        }

        private void button10_Click(object sender, EventArgs e)

        {

            textBox1.Text = textBox1.Text + 5;

        }

        private void button11_Click(object sender, EventArgs e)

        {

            textBox1.Text = textBox1.Text + 6;

        }

        private void button5_Click(object sender, EventArgs e)

        {

            textBox1.Text = textBox1.Text + 7;

        }

        private void button6_Click(object sender, EventArgs e)

        {

            textBox1.Text = textBox1.Text + 8;

        }

        private void button7_Click(object sender, EventArgs e)

        {

            textBox1.Text = textBox1.Text + 9;

        }

Таким же образом кликаем дважды на кнопку «.» в форме. Она будет использоваться для создания десятичной дроби. Пишем следующий код:

private void button18_Click(object sender, EventArgs e)

        {

            textBox1.Text = textBox1.Text + «,»;

        }

Кнопки нажимаются, в TextBox’e отображаются нажатые цифры. Теперь надо научить программу производить с ними какие-либо операции. Как видно из формы, наш калькулятор сможет производить стандартные математические операции: сложение, вычитание, умножение и деление. Для начала мы создадим  в самом начале программы несколько переменных, которые нам для этого понадобятся:

float a, b;

int count;

bool znak = true;

Первым двум переменным будут присваиваться значения, набранные пользователем в калькуляторе. В последствии с ними будут производиться нужные математические операции. Тип float — это тип с плавающей точкой, позволяющий работать с десятичными дробями, что нам, безусловно, нужно при наличии кнопки «.» .

Благодаря второй переменной мы будем давать программе указания, какую именно операцию производить с переменными, описанными выше. Здесь нам не нужна дробь, поэтому обойдёмся целочисленным типом int.

Последняя переменная znak нам понадобится для того, чтобы менять знаки у введённых чисел. Тип bool может иметь два значения — ture и false. Мы представим, что если znak имеет значение true в программе, то это означает, что у числа знак +, если false — число отрицательное и перед собой имеет знак . Изначально в калькуляторе вбиваются положительные числа, поэтому мы сразу присвоили переменной значение true.

Далее мы дважды нажимаем на кнопку «+», обозначающую сложение, на форме и пишем следующий код:

private void button4_Click(object sender, EventArgs e)

        {

            a = float.Parse(textBox1.Text);

            textBox1.Clear();

            count = 1;

            label1.Text = a.ToString() + «+»;

            znak = true;

        }

В строке 3 мы присваиваем первой переменной a то, что будет написано в TextBox’e (а именно число, которое введёт пользователь перед тем, как нажать кнопку «+»).

Затем TextBox очищается, число, введённое пользователем, в нём пропадает (но остаётся в переменной a)

Переменной count присваивается число 1, которая потом укажет программе, что именно операцию сложения надо будет произвести с числами.

Затем в Label записывается число из переменной (то самое, которое изначально ввёл пользователь) и знак плюса. Выглядеть в форме это будет так, как описано ниже.

Пользователь вводит какое-либо число:

Калькулятор Windows Forms на языке C#

Затем нажимает на кнопку «+» и после этого видит:

Калькулятор Windows Forms на языке C#

Кроме того, как бы не было странным с первого взгляда, мы присваиваем переменной znak значение true, хотя выше, в начале кода, мы и так присваивали это же значение. Подробнее данную переменную мы опишем ниже, но смысл в том, что мы присваиваем значение true, когда хотим сделать введённое число отрицательным, если оно положительно, а значение false, когда хотим сделать число положительным, если оно отрицательное. Изначально у нас вводятся положительные числа, сначала первое, потом второе. И если первое число мы сделаем отрицательным, то значение у znak перейдёт в false и тогда получится, что второе слагаемое как бы отрицательное (на практике, просто чтобы поставить перед ним минус, придётся нажать дважды на соответствующую кнопку, чтобы с false значение перешло в true, а затем обратно с true в false, и появился знак минуса).

Подобным образом заполняем код для кнопок «-«, «*» и «/»:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

        private void button8_Click(object sender, EventArgs e)

        {

            a = float.Parse(textBox1.Text);

            textBox1.Clear();

            count = 2;

            label1.Text = a.ToString() + «-«;

          znak = true;

        }

        private void button12_Click(object sender, EventArgs e)

        {

            a = float.Parse(textBox1.Text);

            textBox1.Clear();

            count = 3;

            label1.Text = a.ToString() + «*»;

          znak = true;

        }

        private void button16_Click(object sender, EventArgs e)

        {

            a = float.Parse(textBox1.Text);

            textBox1.Clear();

            count = 4;

            label1.Text = a.ToString() + «/»;

          znak = true;

        }

Разница лишь в значении переменной count и в том, какой знак добавляется в Label’e.

Далее нам понадобится создать функцию, которая будет применять нужные нам математические операции к числам. Назовём её calculate. Но перед этим мы кликнем дважды на кнопку «=» на форме и в коде к ней мы запишем:

private void button19_Click(object sender, EventArgs e)

        {

            calculate();

            label1.Text = «»;

        }

То есть, при нажатии пользователем на кнопку «=», как раз выполнится наша функция подсчёта calculate, и, заодно, очистится Label, так как результат мы в будущем коде выведем в TextBox.

Теперь-таки создаём нашу функцию calculate и пишем следующий код:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

private void calculate()

        {

            switch(count)

            {

                case 1:

                    b = a + float.Parse(textBox1.Text);

                    textBox1.Text = b.ToString();

                    break;

                case 2:

                    b = a float.Parse(textBox1.Text);

                    textBox1.Text = b.ToString();

                    break;

                case 3:

                    b = a * float.Parse(textBox1.Text);

                    textBox1.Text = b.ToString();

                    break;

                case 4:

                    b = a / float.Parse(textBox1.Text);

                    textBox1.Text = b.ToString();

                    break;

                default:

                    break;

            }

        }

Здесь мы используем конструкцию switch-case.

Switch — это оператор управления. Он может включать в себя несколько case’ов. Case — метки, от значения которых зависит, какие операции будут происходить.

Строка switch(count) означает, что именно от значения count будет зависеть, какое действие будет происходить в коде switch’a.

Итак, если count=1 (в коде case 1:), то произойдёт следующее:

После того, как пользователь нажал «+», он, естественно, должен ввести второе слагаемое, что он и делает по стандартному сценарию, а затем нажать кнопку «=» (и в ней, как мы помним, как раз выполнится наша функция).

Как только кнопка «=» будет нажата, программа сложит число из переменной a с тем вторым слагаемым, которое записал пользователь в TextBox, и запишет результат в переменную b (строка 6 кода функции). В строке 7 программа выведет в TextBox результат сложения — переменную b.

Оператор break (строка 8) завершает исполнение кода switch при выполнении кода метки case 1, так как больше нам в нём делать нечего.

Точно так же строится алгоритм при case 2, case 3 и case 4 с той разницей, что в них происходит не сложение, а вычитание, умножение и деление соответственно.

Оператор default срабатывает, если вдруг что-то пойдёт не по плану и count  примет какое-либо иное значение, не описанное в switch. Тогда срабатывает лишь оператор break.

Львиная доля программы готова. Нам надо лишь написать код для трёх оставшихся нетронутыми до этого время кнопок.

Дважды жмём в форме на кнопку «С». Она будет очищать все записи из TextBox’a и Label’a.

Код у неё элементарный:

private void button3_Click(object sender, EventArgs e)

        {

            textBox1.Text = «»;

            label1.Text = «»;

        }

На очереди у нас кнопка «<—«. Она будет удалять последнюю цифру записанного в TextBox’e числа. Код:

private void button2_Click(object sender, EventArgs e)

        {

            int lenght = textBox1.Text.Length 1;

            string text = textBox1.Text;

            textBox1.Clear();

            for (int i = 0; i < lenght; i++)

            {

                textBox1.Text = textBox1.Text + text[i];

            }

        }

Мы вводим новую переменную lenght целочисленного типа и записываем в неё количество символов в TextBox’e минус один символ.

Также мы вводим новую переменную text, в которую полностью заносим текст из TextBox’а. Затем мы очищаем TextBox и вводим цикл for, через который записываем в TextBox строку text, но уже на символ короче.

Например, в TextBox’e записано число 504523

При нажатии на кнопку «<—« в переменную lenght записывается число 5 (6 цифр — 1), в переменную text записывается строка «504523»TextBox очищается, а затем в него по одному записываются символы из text, но в этот раз их будет не 6, а 5, то есть в TextBox’e появится число 50452.

У нас остаётся последняя кнопка, которая отвечает за знак первого слагаемого. Переходим к её коду. Тут мы будет работать с переменной znak, которую описывали выше. Код выглядит вот так:

private void button1_Click(object sender, EventArgs e)

        {

            if(znak==true)

            {

                textBox1.Text = «-« + textBox1.Text;

                znak = false;

            }

            else if (znak==false)

            {

                textBox1.Text=textBox1.Text.Replace(«-«, «»);

                znak = true;

            }

Изначально, как мы помним, у переменной znak стоит значение true. Если мы нажмём на кнопку первый раз, то в TextBox’e перед числом появится знак «-«, а переменной znak будет присвоено  значение false.

Если второй раз нажать на данную кнопку, то, так как znak у нас false, произойдёт второе условие. Здесь используется метод Replace, который заменяет какой-либо кусок строки на другой. В скобках после метода вначале пишется, что будет заменено в строке, а после запятой, то, на что заменять. В данном случае мы заменяем в TextBox’e минус на пустое значение.

Вот и всё, наш калькулятор Windows Forms готов! Можно его тестировать!

Калькулятор Windows Forms на языке C#

Если у Вас возникнут вопросы или просьбы по данной программе, можете оставить комментарий под этой записью. А исходный код калькулятора можно скачать ниже:

Скачать исходник

Создаем калькулятор на C# и WinForms

В сегодняшней статье мы создадим простой калькулятор способный выполнять сложение, вычитание, умножение, а также деление. И все это мы реализуем на языке C# и шаблонах Windows Forms. Так что, давайте приступим.

Шаг 1

Откройте Visual Studio или Visual C# Express Edition и создайте новый проект.

Установите его тип в приложение Windows Forms и задайте имя в приложения Калькулятор. Нажмите кнопку ОК.

Изображение

Должно получиться следующее:

Изображение

Шаг 2

Измените свойство текста формы на Калькулятор, потому что мы не хотим, чтобы наше приложение имело заголовок Form1 при запуске.
Для чего заходим во вкладку свойтва.

Изображение

Шаг 3

Далее во вкладке Вид находим панель элементов или ToolBox.
Поместите элемент управления TextBox на форму и измените его размер. Выполните некоторые изменения в свойствах, как показано на рисунке.

Изображение

Шаг 4

Теперь мы начинаем работать с дисплеем, обычно при запуске калькулятора на нем должно отображаться число 0. В нашем случае это не так. Поэтому мы изменяем свойство Text и записываем в нем 0. Убедитесь, что вы не добавляете никаких пробелов до или после 0.

Второе, что следует отметить, это то, что число выровнено слева, в то время как калькуляторы выравнивают число справа. Найдите свойство TextAlign и измените его на Right.

Вот как будет выглядеть окно.

Изображение

Шаг 5

В окне панели инструментов перетащите кнопку на форму. Измените его свойство Name на n1. Это поможет нам определить, какой номер был нажат. Измените свойство backcolor для кнопки. После изменения цвета мы изменим текст, отображаемый кнопкой, поэтому измените свойство text на 1. Перейдите к свойству шрифта и установите для него значение шрифта Сourier new, а размер, например, 16.

Изображение

Теперь мы можем повторить ту же операцию со всеми остальными девятью кнопками, или мы можем просто скопировать эту кнопку и быстро получить тот же результат. Просто удерживайте клавишу ctrl и перетащите элемент управления.

Измените названия кнопок (или вы можете оставить их как есть и пропустить эту часть). Имена по-прежнему будут n2, n3, n4, n5, n6, n7, n8, n9 и n0.Окно должно выглядеть так.

Изображение

Шаг 6

Дважды нажмите кнопку n1, чтобы перейти к ее обработчику события. Тогда n1_Click — это название этой процедуры. Он сообщает вам, что он выполняется, когда пользователь нажимает кнопку с именем n1. Запишите код, чтобы он был таким:


    private void n1_Click(object sender, EventArgs e)  
    {  
        if (textBox1.Text == "0" && textBox1.Text != null)  
        {  
            textBox1.Text = "1";  
        }  
        else  
        {  
            textBox1.Text = textBox1.Text + "1";  
        }  
    }  

Вы должны повторить код для кнопок n2, n3, n4, n5, n6, n7, n8, n9 и n0, чтобы добавить числа 2,3,4,5,6,7,8,9,0 соответственно.

Теперь запустите приложение и нажмите несколько кнопок:

Изображение

Таким образом, мы создали простой шаблон калькулятора с C# и Windows Forms, в который осталось добавить арифметическую логику.

  • Создано 25.11.2021 10:26:55


  • Михаил Русаков

Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления

Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

В статье «Делаем консольный калькулятор.» мы создавали небольшой калькулятор, который работает в консоли. В этой статье пришло время научиться создавать графический калькулятор на языке C# с помощью Windows Forms.

Сам по себе калькулятор довольно прост, но если вы совсем новичок в создании подобных приложений, тогда будет посложнее. Разработку калькулятора начнем с разработки формы (Windows Forms) приложения. Запускаем Visual Studio и создаем проект:

Создание графического калькулятора

Интерфейс созданного проекта должен выглядеть так:

Создание графического калькулятора

На интерфейсе мы видим: слева панель элементов для нашей формы, справа обозреватель решений и свойства выбранной формы/элемента и по середине виден сам конструктор с формой (по умолчанию он имеет имя «Form1»).

На форму нужно поместить кнопки, текстовое поле, а также надпись. Надпись нужна, чтобы пользователь видел первый операнд. Когда введет нужную цифру, нажмет кнопку, например «+», надпись будет содержать введенное значение.

Все нужные элементы можно найти слева в панели элементов. Чтобы найти текстовое поле просто введите в поиске «textBox» и с помощью мышки перенесите его на свою форму. Для добавления кнопок просто введите в поиске «Button» и перенесите нужное количество кнопок на свою форму. Также добавьте на «ListBox» один пустой «Label»:

Создание графического калькулятора

Изменять свойства формы можно с помощью окна «Свойства» справа внизу. Для этого нажмите на нужную форму, например «Button1» и поменяйте ему свойство «text» на «С»:

Создание графического калькулятора

Добавьте все нужные кнопки. Измените свойство «Font» для элементов TextBox и Label. Цвет кнопок и имя программы меняйте на свое усмотрение.

Создание графического калькулятора

С помощью «MultiLine» измените ширину элемента TextBox:

Создание графического калькулятора

В итоге у нас получилось 19 кнопок Button, 1 TextBox и ещё 1 пустой Label:

Создание графического калькулятора

Теперь посмотрим, как работает калькулятор. Мы используем четыре члена класса. Напишем их в самое начало программы:

    float a, b;
    int oper;
    bool znak = true;

Первые два — это наши операнды, a и b. Третий — это выбранный пользователем оператор. Четвертый — признак знака. Запрограммируем обработчик кнопки «+/-«, изменяющий знак числа. Для этого в форме нажмите на нужную кнопку два раза. Visual Studio переведет вас в нужную секцию кода:

        private void button3_Click(object sender, EventArgs e)
        {

        }

В фигурных скобках пишем код:

            if (znak == true)
            {
                textBox1.Text = "-" + textBox1.Text;
                znak = false;
            }
            else if (znak==false)
            {
                textBox1.Text = textBox1.Text.Replace("-", "");
                znak = true;
            }

Если znak=true, мы меняем знак операнда в textBox1, а если false, то знак числа удаляется из текстового поля.

Для каждой цифровой кнопки обработчик будет следующий:

// Обработчик цифровой кнопки "0"

textBox1.Text = textBox1.Text + 0;

На основе этого кода повесьте на цифровые кнопки от 0 до 9 обработчик событий. Нажмите на нужную цифровую кнопку и впишите код.

Обработчик кнопки операторов «+, -, *, /». Нажмите на нужную кнопку с оператором и впишите код.

            // Обработчик оператора "+"

            a = float.Parse(textBox1.Text);
            textBox1.Clear();
            oper = 1;
            label1.Text = a.ToString() + "+";
            znak = true;

В данном коде мы в переменную «a» записываем значение из текстового поля, попутно преобразовав его в float посредством вызова метода float.Parse(). Далее мы очищаем текстовое поле, чтобы можно было вводить второй операнд. oper = 1 означает присвоение номера оператора (для + — это 1 и так далее по увеличению). Далее заносим в надпись информацию об операнде и операторе.

Обработчик кнопки «,» добавляет запятую в текстовое поле:

textBox1.Text = textBox1.Text + ",";

Далее нам понадобится создать функцию, которая будет применять нужные нам математические операции к числам. Назовём её calculate. Но перед этим мы кликнем дважды на кнопку «=» на форме и в коде к ней мы запишем:

// вызов функции
calculate();
label1.Text = "";

При нажатии пользователем на кнопку «=» выполнится функция подсчёта calculate, и, заодно, очистится Label, так как результат мы в будущем коде выведем в TextBox.

Функция calculate:

        private void calculate()
        {
            switch (oper)
            {
                case 1:
                    b = a + float.Parse(textBox1.Text);
                    textBox1.Text = b.ToString();
                    break;
                case 2:
                    b = a - float.Parse(textBox1.Text);
                    textBox1.Text = b.ToString();
                    break;
                case 3:
                    b = a * float.Parse(textBox1.Text);
                    textBox1.Text = b.ToString();
                    break;
                case 4:

                    if (float.Parse(textBox1.Text) == 0)
                    { textBox1.Text = "Делить на 0 нельзя!"; }
                    else
                    {
                        b = a / float.Parse(textBox1.Text);
                        textBox1.Text = b.ToString();
                    }
                    break;
                default:
                    break;
            }

        }

Здесь мы используем конструкцию switch-case. Нам осталось обработать две кнопки:

Обработчик кнопки «С». Данная кнопка будет очищать все записи из TextBox’a и Label’a. Код кнопки:

textBox1.Text = "";
label1.Text = "";

Кнопка «<–» будет удалять последнюю цифру записанного в TextBox’e числа. Код кнопки:

            int lenght = textBox1.Text.Length - 1;
            string text = textBox1.Text;
            textBox1.Clear();
            for (int i = 0; i < lenght; i++)
            {
                textBox1.Text = textBox1.Text + text[i];
            }

Мы вводим новую переменную lenght целочисленного типа и записываем в неё количество символов в TextBox’e минус один символ.

Также мы вводим новую переменную text, в которую полностью заносим текст из TextBox’а. Затем мы очищаем TextBox и вводим цикл for, через который записываем в TextBox строку text, но уже на символ короче.

Теперь наш графический калькулятор готов к работе. Скомпилируйте программу, нажав на «Пуск». Если все заработало и калькулятор делает вычисления, тогда вы все правильно сделали и теперь можете пользоваться свомим личным графическим калькулятором.

Создание графического калькулятора

В данном уроке мы разработаем с вами калькулятор на C#. Программа будет написана согласно принципам объектно-ориентированного программирования (ООП): будет определен интерфейс для методов, реализующих функционал клавиш математических операций калькулятора, от интерфейса выполним наследование и напишем соответствующий класс и методы. Калькулятор, помимо базовых операций сложения, вычитания, умножения и деления, будет предоставлять возможность выполнять операции: извлечения квадратного корня, извлечения корня произвольной степени, возведения в квадрат, возведения в произвольную степень, вычисления факториала, а также работу с регистром памяти (MRC).

Создание интерфейса.

Создадим в Visual Studio проект на Visual C# Windows Forms. Добавим на форму элемент GroupBox, в который поместим Label. В свойстве Dock, элемента Label, необходимо указать Right, чтобы Label был привязан к правому краю. Связка данных элементов управления будет реализовывать дисплей калькулятора.

Калькулятор также содержит кнопки. Всего их 28 штук.

Программирование калькулятора на C#Реализация интерфейса класса.

Поскольку наш калькулятор будет написан в рамках парадигмы ООП (объектно-ориентированного программирования), то начнем кодирование с описания структуры интерфейса для класса, реализующего математические операции программы.

Добавим в проект класс InterfaceCalc.cs и определим в созданном файле интерфейс InterfaceCalc.

//интерфейс

public interface InterfaceCalc

{

//а — первый аргумент, b — второй

void Put_A(double a); //сохранить а

void Clear_A();

double Multiplication(double b);

double Division(double b);

double Sum(double b);

double Subtraction(double b); //вычитание

double SqrtX(double b);

double DegreeY(double b);

double Sqrt();

double Square();

double Factorial();

double MemoryShow(); //показать содержимое регистра памяти

void Memory_Clear(); //стереть содержимое регистра памяти

//* / + — к регистру памяти

void M_Multiplication(double b);

void M_Division(double b);

void M_Sum(double b);

void M_Subtraction(double b); //вычитание

}

Для выполнения математических операций понадобится два операнда: a и b (например, a + b). Операнд a придется хранить в памяти калькулятора, пока пользователь будет вводить второй аргумент операции. Для сохранения числа a объявим прототип метода void Put_A(double a), для очистки — void Clear_A(). Для умножения, деления, сложения и вычитания чисел a и b соответственно понадобятся методы: double Multiplication(double b), double Division(double b), double Sum(double b), double Subtraction(double b). Вычисление корня степени b из a: double SqrtX(double b). Возведение числа a в степень b: double DegreeY(double b). Вычисление квадратного корня: double Sqrt(). Возведение числа a в квадрат: double Square(). Вычисление факториала a!: double Factorial(). Теперь объявления методов для работы с регистром памяти (MRC) калькулятора. Показать содержимое памяти и очистить его: double MemoryShow(), void Memory_Clear(). M×, M÷, M+ и M- к регистру соответственно: void M_Multiplication(double b), void M_Division(double b), void M_Sum(double b), void M_Subtraction(double b).

Создание класса, реализующего интерфейс InterfaceCalc

Теперь добавим в калькулятор класс, который будет реализовывать написанный ранее интерфейс. Для этого в проекте создадим класс Calc : InterfaceCalc. Как вы видите, здесь используется наследование (оператор «двоеточие»). В данном классе напишем реализацию всех методов, требуемых спецификацией нашего интерфейса.

public class Calc : InterfaceCalc

{

private double a = 0;

private double memory = 0;

public void Put_A(double a)

{

this.a = a;

}

public void Clear_A()

{

a = 0;

}

public double Multiplication(double b)

{

return a * b;

}

public double Division(double b)

{

return a / b;

}

public double Sum(double b)

{

return a + b;

}

public double Subtraction(double b) //вычитание

{

return a — b;

}

public double SqrtX(double b)

{

return Math.Pow(a, 1 / b);

}

public double DegreeY(double b)

{

return Math.Pow(a, b);

}

public double Sqrt()

{

return Math.Sqrt(a);

}

public double Square()

{

return Math.Pow(a, 2.0);

}

public double Factorial()

{

double f = 1;

for (int i = 1; i <= a; i++)

f *= (double)i;

return f;

}

//показать содержимое регистра мамяти

public double MemoryShow()

{

return memory;

}

//стереть содержимое регистра мамяти

public void Memory_Clear()

{

memory = 0.0;

}

//* / + — к регистру памяти

public void M_Multiplication(double b)

{

memory *= b;

}

public void M_Division(double b)

{

memory /= b;

}

public void M_Sum(double b)

{

memory += b;

}

public void M_Subtraction(double b)

{

memory -= b;

}

}

Реализация работы калькулятора

Перейдем к написанию кода в классе Form1.

Объявим два поля:

CalcC;

int k;

Это классовая переменная C для класса Calc и целое число k. С помощью k будем считать количество нажатий кнопки MRC, чтобы при первом нажатии выводить значение регистра памяти на экран, а при последующем повторном — стирать значение регистра.

Далее. Нам понадобится ряд методов, которые будут обеспечивать правильное функционирование калькулятора.

Дисплеем в нашем калькуляторе является Label. Его содержимое — это строка текста. Нажатие на цифровые клавиши — это конкатенация текущего значения строки с символом клавиши. Необходимо исключить дублирование нулей в левой части строки (это делают 2-й и 3-й if в коде ниже), а также не допустить написание цифр, если в Label находится знак «бесконечность» (он появляется, например, при делении на ноль; 1-й if). Для решения данных проблем напишем метод CorrectNumber():

privatevoidCorrectNumber(){//если есть знак «бесконечность» — не даёт писать цифры после негоif(labelNumber.Text.IndexOf(«∞»)!=-1)labelNumber.Text=labelNumber.Text.Substring(0,labelNumber.Text.Length-1);//ситуация: слева ноль, а после него НЕ запятая, тогда ноль можно удалитьif(labelNumber.Text[0]==’0’&& (labelNumber.Text.IndexOf(«,») != 1)) labelNumber.Text = labelNumber.Text.Remove(0, 1);//аналогично предыдущему, только для отрицательного числаif(labelNumber.Text[0]==’-‘)if(labelNumber.Text[1]==’0’&& (labelNumber.Text.IndexOf(«,») != 2)) labelNumber.Text = labelNumber.Text.Remove(1, 1);}

Еще необходим метод, проверяющий: не нажата ли какая-нибудь кнопка калькулятора из математических операций, требующих два операнда. Данная проверка необходима для недопущения нажатия других мат. операций, если какая-либо уже нажата. Код метода CanPress():

privateboolCanPress(){if(!buttonMult.Enabled)returnfalse;if(!buttonDiv.Enabled)returnfalse;if(!buttonPlus.Enabled)returnfalse;if(!buttonMinus.Enabled)returnfalse;if(!buttonSqrtX.Enabled)returnfalse;if(!buttonDegreeY.Enabled)returnfalse;returntrue;}

Также, напишем вспомогательный метод FreeButtons(), который снимает нажатия со всех кнопок математических операций калькулятора, требующих два операнда (умножение, деление, сложение, вычитание, вычисление корня произвольной степени и возведение числа в произвольную степень):

privatevoidFreeButtons(){buttonMult.Enabled=true;buttonDiv.Enabled=true;buttonPlus.Enabled=true;buttonMinus.Enabled=true;buttonSqrtX.Enabled=true;buttonDegreeY.Enabled=true;}

Со вспомогательными методами закончили. Идем дальше.

В конструкторе Form1 создадим экземпляр класса Calc, а также в «дисплей» калькулятора занесем значение ноль.

publicForm1(){InitializeComponent();C=newCalc();labelNumber.Text=»0″;}

Теперь перейдем к кодированию обработчиков нажатий кнопок калькулятора. Кнопка «Очистка» (CE):

privatevoidbuttonClear_Click(objectsender,EventArgse){labelNumber.Text=»0″;C.Clear_A();FreeButtons();k=0;}

В «дисплей» записывается ноль, переменная a стирается, нажатия с кнопок математических операций снимаются и k обнуляется.

Кнопка изменения знака у числа «+/-«:

privatevoidbuttonChangeSign_Click(objectsender,EventArgse){if(labelNumber.Text[0]==’-‘)labelNumber.Text=labelNumber.Text.Remove(0,1);elselabelNumber.Text=»-«+labelNumber.Text;}

Кнопка «запятая» (будет добавлена, если ее еще нет и на «дисплее» нет знака бесконечность):

privatevoidbuttonPoint_Click(objectsender,EventArgse){if((labelNumber.Text.IndexOf(«,»)==-1)&& (labelNumber.Text.IndexOf(«∞») == -1)) labelNumber.Text += «,»;}

Теперь цифровые клавиши 0, 1, 2, 3, 4, 5, 6, 7, 8, 9:

privatevoidbutton0_Click(objectsender,EventArgse){labelNumber.Text+=»0″;CorrectNumber();}privatevoidbutton1_Click(objectsender,EventArgse){labelNumber.Text+=»1″;CorrectNumber();}privatevoidbutton2_Click(objectsender,EventArgse){labelNumber.Text+=»2″;CorrectNumber();}privatevoidbutton3_Click(objectsender,EventArgse){labelNumber.Text+=»3″;CorrectNumber();}privatevoidbutton4_Click(objectsender,EventArgse){labelNumber.Text+=»4″;CorrectNumber();}privatevoidbutton5_Click(objectsender,EventArgse){labelNumber.Text+=»5″;CorrectNumber();}privatevoidbutton6_Click(objectsender,EventArgse){labelNumber.Text+=»6″;CorrectNumber();}privatevoidbutton7_Click(objectsender,EventArgse){labelNumber.Text+=»7″;CorrectNumber();}privatevoidbutton8_Click(objectsender,EventArgse){labelNumber.Text+=»8″;CorrectNumber();}privatevoidbutton9_Click(objectsender,EventArgse){labelNumber.Text+=»9″;CorrectNumber();}

Кнопка «Равно»:

private void buttonCalc_Click(object sender, EventArgs e)

{

if (!buttonMult.Enabled)

labelNumber.Text = C.Multiplication(Convert.ToDouble(labelNumber.Text)).ToString();

if (!buttonDiv.Enabled)

labelNumber.Text = C.Division(Convert.ToDouble(labelNumber.Text)).ToString();

if (!buttonPlus.Enabled)

labelNumber.Text = C.Sum(Convert.ToDouble(labelNumber.Text)).ToString();

if (!buttonMinus.Enabled)

labelNumber.Text = C.Subtraction(Convert.ToDouble(labelNumber.Text)).ToString();

if (!buttonSqrtX.Enabled)

labelNumber.Text = C.SqrtX(Convert.ToDouble(labelNumber.Text)).ToString();

if (!buttonDegreeY.Enabled)

labelNumber.Text = C.DegreeY(Convert.ToDouble(labelNumber.Text)).ToString();

C.Clear_A();

FreeButtons();

k = 0;

}

В зависимости от того, какая из кнопок математических операций нажата, будет вызван соответствующий метод из класса Calc, вычисляющий данную функцию, и результат выведется в Label.

Далее кнопки математических операций. Сработают только в том случае, если другие в данный момент не нажаты (CanPress() вернет true):

//кнопка УмножениеprivatevoidbuttonMult_Click(objectsender,EventArgse){if(CanPress()){C.Put_A(Convert.ToDouble(labelNumber.Text));buttonMult.Enabled=false;labelNumber.Text=»0″;}}//кнопка ДелениеprivatevoidbuttonDiv_Click(objectsender,EventArgse){if(CanPress()){C.Put_A(Convert.ToDouble(labelNumber.Text));buttonDiv.Enabled=false;labelNumber.Text=»0″;}}//кнопка СложениеprivatevoidbuttonPlus_Click(objectsender,EventArgse){if(CanPress()){C.Put_A(Convert.ToDouble(labelNumber.Text));buttonPlus.Enabled=false;labelNumber.Text=»0″;}}//кнопка ВычитаниеprivatevoidbuttonMinus_Click(objectsender,EventArgse){if(CanPress()){C.Put_A(Convert.ToDouble(labelNumber.Text));buttonMinus.Enabled=false;labelNumber.Text=»0″;}}//кнопка Корень произвольной степениprivatevoidbuttonSqrtX_Click(objectsender,EventArgse){if(CanPress()){C.Put_A(Convert.ToDouble(labelNumber.Text));buttonSqrtX.Enabled=false;labelNumber.Text=»0″;}}//кнопка Возведение в произвольную степеньprivatevoidbuttonDegreeY_Click(objectsender,EventArgse){if(CanPress()){C.Put_A(Convert.ToDouble(labelNumber.Text));buttonDegreeY.Enabled=false;labelNumber.Text=»0″;}}//кнопка Корень квадратныйprivatevoidbuttonSqrt_Click(objectsender,EventArgse){if(CanPress()){C.Put_A(Convert.ToDouble(labelNumber.Text));labelNumber.Text=C.Sqrt().ToString();C.Clear_A();FreeButtons();}}//кнопка Квадрат числаprivatevoidbuttonSquare_Click(objectsender,EventArgse){if(CanPress()){C.Put_A(Convert.ToDouble(labelNumber.Text));labelNumber.Text=C.Square().ToString();C.Clear_A();FreeButtons();}}//кнопка ФакториалprivatevoidbuttonFactorial_Click(objectsender,EventArgse){if(CanPress()){if((Convert.ToDouble(labelNumber.Text)==(int)(Convert.ToDouble(labelNumber.Text)))&& ((Convert.ToDouble(labelNumber.Text) >= 0.0))) { C.Put_A(Convert.ToDouble(labelNumber.Text));labelNumber.Text=C.Factorial().ToString();C.Clear_A();FreeButtons();}elseMessageBox.Show(«Число должно быть >= 0 и целым!»);}}

Калькулятор вычислит факториал только в том случае, если текущее введенное число целое и больше, либо равно нулю.

Кнопки математических операций над регистром памяти (MRC):

//кнопка М+privatevoidbuttonMPlus_Click(objectsender,EventArgse){C.M_Sum(Convert.ToDouble(labelNumber.Text));}//кнопка М-privatevoidbuttonMMinus_Click(objectsender,EventArgse){C.M_Subtraction(Convert.ToDouble(labelNumber.Text));}//кнопка М*privatevoidbuttonMMult_Click(objectsender,EventArgse){C.M_Multiplication(Convert.ToDouble(labelNumber.Text));}//кнопка М/privatevoidbuttonMDiv_Click(objectsender,EventArgse){C.M_Division(Convert.ToDouble(labelNumber.Text));}

И последняя кнопка — «MRC». Она показывает содержимое регистра памяти на экран, а при повторном нажатии стирает его:

privatevoidbuttonMRC_Click(objectsender,EventArgse){if(CanPress()){k++;if(k==1)labelNumber.Text=C.MemoryShow().ToString();if(k==2){C.Memory_Clear();labelNumber.Text=»0″;k=0;}}}

На этом написание калькулятора на C# закончено. Спасибо за прочтение статьи!

How to Make a Calculator in C# Windows Form Application

How to Make a Calculator in C# Windows Form Application


In this post we will see How to create a Simple Calculator in C# with windows form application using Visual Studio.
Download Calculator Code C# (Calculator.zip)

How to Make a Calculator in C# Windows Form Application

How to Make a Calculator in C# Windows Form Application

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Calculator
{
    public partial class Form1 : Form
    {
        Double resultValue = 0;
        String operationPerformed = "";
        bool isOperationPerformed = false;
        public Form1()
        {
            InitializeComponent();
        }

        private void button_click(object sender, EventArgs e)
        {
            if ((textBox_Result.Text == "0") || (isOperationPerformed))
                textBox_Result.Clear();

            isOperationPerformed = false;
            Button button = (Button)sender;
            if (button.Text == ".")
            { 
               if(!textBox_Result.Text.Contains("."))
                   textBox_Result.Text = textBox_Result.Text + button.Text;

            }else
            textBox_Result.Text = textBox_Result.Text + button.Text;


        }

        private void operator_click(object sender, EventArgs e)
        {
            Button button = (Button)sender;

            if (resultValue != 0)
            {
                button15.PerformClick();
                operationPerformed = button.Text;
                labelCurrentOperation.Text = resultValue + " " + operationPerformed;
                isOperationPerformed = true;
            }
            else
            {

                operationPerformed = button.Text;
                resultValue = Double.Parse(textBox_Result.Text);
                labelCurrentOperation.Text = resultValue + " " + operationPerformed;
                isOperationPerformed = true;
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            textBox_Result.Text = "0";
        }

        private void button5_Click(object sender, EventArgs e)
        {
            textBox_Result.Text = "0";
            resultValue = 0;
        }

        private void button15_Click(object sender, EventArgs e)
        {
            switch (operationPerformed)
            {
                case "+":
                    textBox_Result.Text = (resultValue + Double.Parse(textBox_Result.Text)).ToString();
                    break;
                case "-":
                    textBox_Result.Text = (resultValue - Double.Parse(textBox_Result.Text)).ToString();
                    break;
                case "*":
                    textBox_Result.Text = (resultValue * Double.Parse(textBox_Result.Text)).ToString();
                    break;
                case "/":
                    textBox_Result.Text = (resultValue / Double.Parse(textBox_Result.Text)).ToString();
                    break;
                default:
                    break;
            }
            resultValue = Double.Parse(textBox_Result.Text);
            labelCurrentOperation.Text = "";
        }
    }
}
//How to Create a Calculator in Visual Studio C#
//

Form1.Designer.cs

namespace Calculator
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
            this.buttonOne = new System.Windows.Forms.Button();
            this.button1 = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            this.button3 = new System.Windows.Forms.Button();
            this.button4 = new System.Windows.Forms.Button();
            this.button5 = new System.Windows.Forms.Button();
            this.button6 = new System.Windows.Forms.Button();
            this.button7 = new System.Windows.Forms.Button();
            this.button8 = new System.Windows.Forms.Button();
            this.button9 = new System.Windows.Forms.Button();
            this.button11 = new System.Windows.Forms.Button();
            this.button12 = new System.Windows.Forms.Button();
            this.button13 = new System.Windows.Forms.Button();
            this.button14 = new System.Windows.Forms.Button();
            this.button15 = new System.Windows.Forms.Button();
            this.button16 = new System.Windows.Forms.Button();
            this.button17 = new System.Windows.Forms.Button();
            this.button19 = new System.Windows.Forms.Button();
            this.textBox_Result = new System.Windows.Forms.TextBox();
            this.labelCurrentOperation = new System.Windows.Forms.Label();
            this.SuspendLayout();
            // 
            // buttonOne
            // 
            this.buttonOne.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.buttonOne.Location = new System.Drawing.Point(22, 73);
            this.buttonOne.Name = "buttonOne";
            this.buttonOne.Size = new System.Drawing.Size(45, 45);
            this.buttonOne.TabIndex = 0;
            this.buttonOne.Text = "7";
            this.buttonOne.UseVisualStyleBackColor = true;
            this.buttonOne.Click += new System.EventHandler(this.button_click);
            // 
            // button1
            // 
            this.button1.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.button1.Location = new System.Drawing.Point(73, 73);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(45, 45);
            this.button1.TabIndex = 1;
            this.button1.Text = "8";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button_click);
            // 
            // button2
            // 
            this.button2.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.button2.Location = new System.Drawing.Point(124, 73);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(45, 45);
            this.button2.TabIndex = 2;
            this.button2.Text = "9";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button_click);
            // 
            // button3
            // 
            this.button3.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.button3.Location = new System.Drawing.Point(175, 73);
            this.button3.Name = "button3";
            this.button3.Size = new System.Drawing.Size(45, 45);
            this.button3.TabIndex = 3;
            this.button3.Text = "/";
            this.button3.UseVisualStyleBackColor = true;
            this.button3.Click += new System.EventHandler(this.operator_click);
            // 
            // button4
            // 
            this.button4.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.button4.Location = new System.Drawing.Point(226, 73);
            this.button4.Name = "button4";
            this.button4.Size = new System.Drawing.Size(53, 45);
            this.button4.TabIndex = 4;
            this.button4.Text = "CE";
            this.button4.UseVisualStyleBackColor = true;
            this.button4.Click += new System.EventHandler(this.button4_Click);
            // 
            // button5
            // 
            this.button5.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.button5.Location = new System.Drawing.Point(226, 124);
            this.button5.Name = "button5";
            this.button5.Size = new System.Drawing.Size(53, 45);
            this.button5.TabIndex = 9;
            this.button5.Text = "C";
            this.button5.UseVisualStyleBackColor = true;
            this.button5.Click += new System.EventHandler(this.button5_Click);
            // 
            // button6
            // 
            this.button6.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.button6.Location = new System.Drawing.Point(175, 124);
            this.button6.Name = "button6";
            this.button6.Size = new System.Drawing.Size(45, 45);
            this.button6.TabIndex = 8;
            this.button6.Text = "*";
            this.button6.UseVisualStyleBackColor = true;
            this.button6.Click += new System.EventHandler(this.operator_click);
            // 
            // button7
            // 
            this.button7.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.button7.Location = new System.Drawing.Point(124, 124);
            this.button7.Name = "button7";
            this.button7.Size = new System.Drawing.Size(45, 45);
            this.button7.TabIndex = 7;
            this.button7.Text = "6";
            this.button7.UseVisualStyleBackColor = true;
            this.button7.Click += new System.EventHandler(this.button_click);
            // 
            // button8
            // 
            this.button8.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.button8.Location = new System.Drawing.Point(73, 124);
            this.button8.Name = "button8";
            this.button8.Size = new System.Drawing.Size(45, 45);
            this.button8.TabIndex = 6;
            this.button8.Text = "5";
            this.button8.UseVisualStyleBackColor = true;
            this.button8.Click += new System.EventHandler(this.button_click);
            // 
            // button9
            // 
            this.button9.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.button9.Location = new System.Drawing.Point(22, 124);
            this.button9.Name = "button9";
            this.button9.Size = new System.Drawing.Size(45, 45);
            this.button9.TabIndex = 5;
            this.button9.Text = "4";
            this.button9.UseVisualStyleBackColor = true;
            this.button9.Click += new System.EventHandler(this.button_click);
            // 
            // button11
            // 
            this.button11.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.button11.Location = new System.Drawing.Point(175, 175);
            this.button11.Name = "button11";
            this.button11.Size = new System.Drawing.Size(45, 45);
            this.button11.TabIndex = 13;
            this.button11.Text = "-";
            this.button11.UseVisualStyleBackColor = true;
            this.button11.Click += new System.EventHandler(this.operator_click);
            // 
            // button12
            // 
            this.button12.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.button12.Location = new System.Drawing.Point(124, 175);
            this.button12.Name = "button12";
            this.button12.Size = new System.Drawing.Size(45, 45);
            this.button12.TabIndex = 12;
            this.button12.Text = "3";
            this.button12.UseVisualStyleBackColor = true;
            this.button12.Click += new System.EventHandler(this.button_click);
            // 
            // button13
            // 
            this.button13.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.button13.Location = new System.Drawing.Point(73, 175);
            this.button13.Name = "button13";
            this.button13.Size = new System.Drawing.Size(45, 45);
            this.button13.TabIndex = 11;
            this.button13.Text = "2";
            this.button13.UseVisualStyleBackColor = true;
            this.button13.Click += new System.EventHandler(this.button_click);
            // 
            // button14
            // 
            this.button14.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.button14.Location = new System.Drawing.Point(22, 175);
            this.button14.Name = "button14";
            this.button14.Size = new System.Drawing.Size(45, 45);
            this.button14.TabIndex = 10;
            this.button14.Text = "1";
            this.button14.UseVisualStyleBackColor = true;
            this.button14.Click += new System.EventHandler(this.button_click);
            // 
            // button15
            // 
            this.button15.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.button15.Location = new System.Drawing.Point(226, 175);
            this.button15.Name = "button15";
            this.button15.Size = new System.Drawing.Size(53, 96);
            this.button15.TabIndex = 19;
            this.button15.Text = "=";
            this.button15.UseVisualStyleBackColor = true;
            this.button15.Click += new System.EventHandler(this.button15_Click);
            // 
            // button16
            // 
            this.button16.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.button16.Location = new System.Drawing.Point(175, 226);
            this.button16.Name = "button16";
            this.button16.Size = new System.Drawing.Size(45, 45);
            this.button16.TabIndex = 18;
            this.button16.Text = "+";
            this.button16.UseVisualStyleBackColor = true;
            this.button16.Click += new System.EventHandler(this.operator_click);
            // 
            // button17
            // 
            this.button17.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.button17.Location = new System.Drawing.Point(124, 226);
            this.button17.Name = "button17";
            this.button17.Size = new System.Drawing.Size(45, 45);
            this.button17.TabIndex = 17;
            this.button17.Text = ".";
            this.button17.UseVisualStyleBackColor = true;
            this.button17.Click += new System.EventHandler(this.button_click);
            // 
            // button19
            // 
            this.button19.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.button19.Location = new System.Drawing.Point(22, 226);
            this.button19.Name = "button19";
            this.button19.Size = new System.Drawing.Size(96, 45);
            this.button19.TabIndex = 15;
            this.button19.Text = "0";
            this.button19.UseVisualStyleBackColor = true;
            this.button19.Click += new System.EventHandler(this.button_click);
            // 
            // textBox_Result
            // 
            this.textBox_Result.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.textBox_Result.Location = new System.Drawing.Point(22, 40);
            this.textBox_Result.Name = "textBox_Result";
            this.textBox_Result.Size = new System.Drawing.Size(257, 29);
            this.textBox_Result.TabIndex = 20;
            this.textBox_Result.Text = "0";
            this.textBox_Result.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
            // 
            // labelCurrentOperation
            // 
            this.labelCurrentOperation.AutoSize = true;
            this.labelCurrentOperation.BackColor = System.Drawing.SystemColors.Window;
            this.labelCurrentOperation.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.labelCurrentOperation.ForeColor = System.Drawing.SystemColors.ControlDark;
            this.labelCurrentOperation.Location = new System.Drawing.Point(18, 13);
            this.labelCurrentOperation.Name = "labelCurrentOperation";
            this.labelCurrentOperation.Size = new System.Drawing.Size(0, 24);
            this.labelCurrentOperation.TabIndex = 21;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(305, 291);
            this.Controls.Add(this.labelCurrentOperation);
            this.Controls.Add(this.textBox_Result);
            this.Controls.Add(this.button15);
            this.Controls.Add(this.button16);
            this.Controls.Add(this.button17);
            this.Controls.Add(this.button19);
            this.Controls.Add(this.button11);
            this.Controls.Add(this.button12);
            this.Controls.Add(this.button13);
            this.Controls.Add(this.button14);
            this.Controls.Add(this.button5);
            this.Controls.Add(this.button6);
            this.Controls.Add(this.button7);
            this.Controls.Add(this.button8);
            this.Controls.Add(this.button9);
            this.Controls.Add(this.button4);
            this.Controls.Add(this.button3);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.buttonOne);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.MaximizeBox = false;
            this.Name = "Form1";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "Calculator";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button buttonOne;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Button button2;
        private System.Windows.Forms.Button button3;
        private System.Windows.Forms.Button button4;
        private System.Windows.Forms.Button button5;
        private System.Windows.Forms.Button button6;
        private System.Windows.Forms.Button button7;
        private System.Windows.Forms.Button button8;
        private System.Windows.Forms.Button button9;
        private System.Windows.Forms.Button button11;
        private System.Windows.Forms.Button button12;
        private System.Windows.Forms.Button button13;
        private System.Windows.Forms.Button button14;
        private System.Windows.Forms.Button button15;
        private System.Windows.Forms.Button button16;
        private System.Windows.Forms.Button button17;
        private System.Windows.Forms.Button button19;
        private System.Windows.Forms.TextBox textBox_Result;
        private System.Windows.Forms.Label labelCurrentOperation;
    }
}

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace Calculator
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

In the previous lesson, Introduction to Windows Forms applications, we introduced Windows Forms and created a
window with a text label. In today’s C# .NET tutorial, we’re going to take a
look at events and create a simple calculator. It’ll look like this:

Calculator in C# .NET Windows Forms

Form preparation

Create a new Windows Forms project named Calculator. We’ll
rename the form to CalculatorForm. We usually start our
applications with form design. From the Toolbox, we’ll drag a few controls into
it. We’re going to need:

  • 2x Label
  • 1x Button
  • 2x NumericUpDown
  • 1x ComboBox

Label

We already know the Label, it’s simply a text label.

If we don’t use a control in the code, we don’t have to name it. If we do, we
should set the Name property of it (in the Properties window, the
property name is in parentheses (Name)), then we’ll be able to access this
control using this name. I recommend switching the properties from the
categorized view to alphabetical order (first 2 icons in the Properties window),
you’ll find properties faster. Name is the name of the control,
Text is what is written on the control. This logically implies that
we can have multiple controls with the same text on a form, but they have to
have different names.

One label will only serve as a label with the text "=", so let’s
set it. The second Label will be used for displaying the result, and since we
want to enter the value into it programmatically, we’ll set its
Name property to resultLabel. We’ll set the text to
"0". We can also increase the font to 10.

Button

The button is simply a button that calls a method (more precisely, an event)
when clicked. In this case, we’ll name this button as
calculateButton and we set its Text to
"Calculate". We’ll assign the event to the button later.

NumericUpDown

NumericUpDown is the first control for entering a value we’re
going to introduce. By default, we can only enter an integer in it. We can
change this behavior by setting the DecimalPlaces property, which
specifies the number of decimal places. We’ll set this value to 2
for both controls we put in our form. We also set their Minimum and
Maximum properties. In our case, the minimum should be some low
value and the maximum some high value, let’s say -1000000 and
1000000. To use the maximum values of a given data type, we’d have
to set the limits in the form code using the MaxValue and
MinValue properties of the respective data type.

The advantage of entering numbers using this control is that the user isn’t
able to enter any nonsense value. If we parsed the number from a
TextBox (which we’ll show you in the next lessons), our application
might crash when it gets an invalid value. It’s always easier to choose the
right control than to check the user’s input.

We’ll name the controls as number1NumericUpDown and
number2NumericUpDown. Note that the name should always contain the
control type. For example, we can have both ageLabel and
ageNumericUpDown, where ageLabel is the label of the
age field, and ageNumericUpDown is the field. Moreover, it makes
easier to orientate in the code. Sometimes names as numberNmr,
calculateBtn, etc. are used as well.

ComboBox

We’re almost there. ComboBox is a drop-down list with several
predefined items. The items can be either added in the designer or specified in
the code, even while the program is running. This applies to all controls — all
their properties from the designer can also be set in the code. However, some
advanced properties can only be set from the code and aren’t present in the
designer.

We’ll name the control operationComboBox and then click the
«…» button in the Items property. Inside the newly opened window,
we’ll list the options that can be selected in the comboBox. We write each
option on a separated line. In our case, those options are +,
-, *, /.

ComboBox items from C# .NET in Visual Studio

The items don’t have to be strings, we can pass objects as well.
We’ll show this later.

Unfortunately, the selected item can only be set from the code.

We’ll arrange the controls on the form as shown at the beginning of this
lesson.

Form code

We’ll move to the source code of the form. We already know we do this by
pressing Ctrl + Alt + 0 or by right-clicking on
the form and selecting View Code.

Inside the form constructor, below the InitializeComponents()
method call, we’ll set the selected item of the operationComboBox.
To do this, we’ll set the SelectedIndex property to 0,
thus the first item:

public CalculatorForm()
{
    InitializeComponent();
    operationComboBox.SelectedIndex = 0;
}

Of course, we can access all the form’s items from the form.

Into the constructor, we write the code that should be executed right after
the form is created. When you run the app, adding will be selected as the
operation:

Selecting a ComboBox item in C# .NET

Event handler

Now all we have to do is to respond to the button’s click event. We’ll move
back from the code to the form again, then we’ll double-click the button. A new
method will be automatically added into the code:

private void calculateButton_Click(object sender, EventArgs e)
{

}

If you’ve read the C# .NET object-oriented tutorial,
the method header should remind you of EventHandler. In the
CalculatorForm.Designer.cs file, we can find code that assigns this
method to the button’s event. In case you don’t understand the previous
sentences, it doesn’t mind at all. All you need to know is this method is called
when the button is clicked.

Let’s go back to the designer (Shift + F7) to select
the button. In the Properties window, we can switch between properties
and events using the buttons highlighted in red below:

Events in Visual Studio

Here we see our Click event. This is the place from which we’re
able to remove it or add it again. Some controls have special events for which
we can generate methods from here.

Never delete events just by removing the handler method from the
code. The designer would stop working, and you’d have to fix its file
(specifically, remove the assignment of a no longer existent method to the
event). The only correct way is to use the designer.

Calculation

Let’s move to the calculation itself. The code won’t be complicated at all.
We’ll simply just use conditions for the operationComboBox items
and calculate the result inside the event handler of the button accordingly.
Then we’ll set the result as the text of resultLabel. We shouldn’t
forget to handle division by zero.

The event handling method’s code may look like this:

private void calculateButton_Click(object sender, EventArgs e)
{
    
    string operation = operationComboBox.SelectedItem.ToString();
    double number1 = Convert.ToDouble(number1NumericUpDown.Value);
    double number2 = Convert.ToDouble(number2NumericUpDown.Value);
    double result = 0;

    
    if (operation == "+")
        result = number1 + number2;
    else if (operation == "-")
        result = number1 - number2;
    else if (operation == "*")
        result = number1 * number2;
    else if (operation == "/")
    {
        if (number2 != 0)
            result = number1 / number2;
        else
            MessageBox.Show("You can't divide by zero");
    }
    resultLabel.Text = result.ToString();
}

First, we store the values from the controls in variables to make the code
more readable. We access the selected comboBox item using the
SelectedItem property, which is of the object type.
This means we have to convert it to string in our case. Similarly,
we could also use just the item index using SelectedIndex. Since
NumericUpDown returns the value in its Value property
which is of the decimal type, we must convert it to the
double type using the Convert class.

For the case of zero divisor, we display a MessageBox using the
static class of the same name and calling the Show() method.
Finally, we display the result in resultLabel. Unlike the console,
where we could simply print the numbers, we must first convert the numbers to
string here.

You can also set the Icon property of the form (by selecting the
icon file), Text to «Calculator» and StartPosition to
CenterScreen. Like this, the form will be created in the center of
the screen. If we set FormBorderStyle to FixedSingle,
the form can’t be resized, which fits our application. We can also disable
window maximization using the MaximizeBox property.

The code is available in the article’s attachment as always. In the next
lesson, Birthday Reminder — Designing Forms, we’ll create a more complex app using multiple forms — a
birthday reminder.

Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.

Одна из задач, задаваемых студентам по программированию, это создание калькулятора. Раскрою вам небольшой секрет: немало практических, курсовых и лабораторных работ на C++, C# и Java можно и не делать самостоятельно – есть готовые решения в сети. Однако, я был несколько удивлен, что для такого распространенного задания, как визуальный калькулятор на C++ нет такого готового решения. Ну что ж, нет, так нет, давайте напишем его сами.

Итак, как в большинстве проектов, все начинается с создания приложения Windows Forms, а уже в нем – с редактирования формы. У нас получилась вот такая:


Проект для VS2015

В чем будем считать и хранить числа? Я выбрал тип double – точности его нам вполне хватит; это все же студенческая работа, а не для точных инженерных расчетов. Дальше определимся с тем, сколько чисел и операций будем хранить в памяти. Предположим, штук двадцать: тогда надо создать два массива – один для чисел, а другой для операций между ними.

static array<double> ^mass = gcnew array<double>{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
static array<int> ^ukaz = gcnew array<int>{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

Почему мы воспользовались указателями, а не просто создали глобальные переменные за пределами windows forms? Дело в том, что, использование глобальных переменных – это плохой тон при программировании, и очень часто преподаватели против данной практики студентов.

В нашей программе будут три основных метода: vvod — принимает цифру (нажатую кнопку) в качестве аргумента и добавляет её к числу. ravno — нажатие на кнопку равно — все считает, ravno2 — это нажатие на кнопку знака. Факториал, деление единицы на число и корень квадратные — там реализуются методы сразу при нажатии все обрабатывается.

Добавим также флаг для памяти:

static int mem_flag=0;

И еще систему флагов:

//переменные для памяти
static double memory_znachenie = 0.0;
static int memory_status = 0;
//предыдущая клавиша
static int pred_klav = 0;
static int flag_ravno = 0;
static int put = 0;

Вот, например, как у нас будет выглядеть метод vvod():

//ввод цифр на экран
private: System::Void	vvod (double pr) {         
if (pred_klav==0) {
String^ s = textBox1->Text;
int dl = s->Length;
if (dl<10) {
String^ st = s + Convert::ToString(pr);
textBox1->Text = st;
mass[mem_flag] = Convert::ToDouble(textBox1->Text);
textBox1->Text = Convert::ToString(mass[mem_flag]);
pred_klav = 0;
}
}
else {
String^ st = Convert::ToString(pr);
textBox1->Text = st;
mass[mem_flag] = Convert::ToDouble(textBox1->Text);
textBox1->Text = Convert::ToString(mass[mem_flag]);
pred_klav = 0;
}
}

Здесь мы проверяем, какая клавиша в нашем калькуляторе была нажата перед этим – цифра, арифметическая операция или знак равно. Далее получаем из текстбокса значение, конвертируем предыдущее из массива, конкатенируем строки, потом обратно в double и обновляем значение массива. Также в этом методе мы проверяем длину числа – мы поставили ограничение на 10 знаков.

Обработка кнопки равно – то есть метод вычисления – также не представляет сложности. Пользуясь оператором ветвления switch перебираем все варианты.

Также реализуем собственный класс для обработки ошибок. Зачем это надо? Дело в том, что мы оперируем с числами типа double, а они не выбрасывают некоторые стандартные исключения, например – деление на ноль. Также мы предусмотрим обработку переполнения и вычисления квадратного корня из отрицательного числа. На вход конструкторов этого класса будем принимать пару чисел. Выводятся ошибки при:

  1. взятии корня четной степени из отрицательного числа
  2. логарифмировании отрицательного числа и нуля
  3. делении на нуль.
  4. переполнении (калькулятор все же не бесконечный)

Также не забудем и обработку клавиши запятой. Для этого проверяем, есть ли она уже во введённом числе:

MarshalString(s, s2);
int pos = s2.find(",") ;
if (pos==-1) { }

Вот такие основные моменты надо знать для написания данной программы. Ну а если вы не можете самостоятельно написать визуальный калькулятор на C++, то обратитесь ко мне. Актуальную цену за архив с готовой программой и исходниками с подробными комментариями в настоящий моент 500 рублей. Это будет проект в Visual Studio C++ 2010 — он откроется в любой другой версии студии не ниже 2010. Также есть проект для Visual Studio 2015.

Мой калькулятор реализует все основные функции: сложение, вычитание, деление, умножение, факториал, возведение в степень, извлечение квадратного корня, вычисление 1/x, функции памяти (занести в память, вывести содержимое памяти, очистить память).

Обновление

Добавились новые функции в калькуляторе. А именно:

  • Извлечение корня четной и нечетной степени из числа
  • Вычисление логарифма по любому основанию
  • Вычисление экспоненты

Если вам требуется реализация других функций, то это делается за отдельную плату. Пишите на почту up777up@yandex.ru, стучитесь vk.com/idup7, @upreadru или по другим контактам.


Автор этого материала — я — Пахолков Юрий. Я оказываю услуги по написанию программ на языках Java, C++, C# (а также консультирую по ним) и созданию сайтов. Работаю с сайтами на CMS OpenCart, WordPress, ModX и самописными. Кроме этого, работаю напрямую с JavaScript, PHP, CSS, HTML — то есть могу доработать ваш сайт или помочь с веб-программированием. Пишите сюда.

тегистатьи IT, си плюс плюс, visual studio, калькулятор

Читайте также:

  • Морской бой на Java с исходниками

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

A calculator lying on top of paper 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.

  1. 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.
    Dropdown button to open design view/canvas
  2. In the Toolbox, search for a Button UI element. Click and drag a button onto the canvas.
  3. 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

    One button added onto the winforms canvas
  4. Add 19 more buttons to the canvas to represent the other numbers, operators, and functions of the calculator.
  5. 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

    button0

    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

  6. Rearrange the order of the buttons to replicate the look of a standard calculator. Keep all the buttons the same size.
    Multiple calculator buttons on the canvas
  7. You can also highlight some buttons and change their color to one of your choice, using the BackColor property in the properties window.
  8. 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.
    Properties window BackColor dropdown, and buttons on the canvas with different colors

How to Add the Output Result Label

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

  1. In the Toolbox, drag a Panel UI element onto the canvas.
  2. 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.
    White Panel UI element on the canvas
  3. In the Toolbox, drag a TextBox UI element onto the canvas.
  4. Highlight the textbox. In the properties window, change the following properties to the new value:

    Property

    New Value

    name

    textBoxOutput

    BorderStyle

    None

    Text

    TextAlign

    Right

    Enabled

    False

    BackColor

    White

  5. Position the textbox inside the panel.
    Textbox UI element on the canvas

How to Add the Calculation Logic

Add code to execute the calculation logic when the user clicks on 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’re not familiar with them.
     public partial class Form1 : Form
    {
        private string currentCalculation = "";

         public Form1()
        {
            InitializeComponent();
        }
    }

  3. 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)
    {

     }

  4. 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)
    {
        // This adds the number or operator to the string calculation
        currentCalculation += (sender as Button).Text;

         // Display the current calculation back to the user
        textBoxOutput.Text = currentCalculation;
    }

  5. 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.
    Button highlighted showing the events window. button_Click() is selected for the Click event.

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 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("&divide;", "/");

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

  2. 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.
  3. 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; 
  4. 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.
    Winforms Click event for 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.

  1. 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)
    {
        // Reset the calculation and empty the textbox
        textBoxOutput.Text = "0";
        currentCalculation = "";
    }
  2. On the canvas, highlight the Clear button, and navigate to the Events Window.
  3. Find the Click event. Change the value to button_Clear_Click.
    Click event with the button_Clear_Click function selected
  4. 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 the calculation is not empty, remove the last number/operator entered
        if (currentCalculation.Length > 0)
        {
            currentCalculation = currentCalculation.Remove(currentCalculation.Length - 1, 1);
        }

         // Re-display the calculation onto the screen
        textBoxOutput.Text = currentCalculation;
    }

  5. On the canvas, highlight the Clear Entry button, and navigate to the Events Window.
  6. Find the Click event. Change the value to button_ClearEntry_Click.
    Click event with the button_ClearEntry_Click function selected

How to Run the Calculator Application

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

  1. Click on the green play button at the top of the Visual Studio application.
    A Winforms app with the green play button highlighted
  2. 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.
    Calculator at runtime

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.

Понравилась статья? Поделить с друзьями:

Вот еще несколько интересных статей:

  • Как нарисовать линию в windows form
  • Как написать калькулятор в windows form
  • Как нарисовать график в windows forms c
  • Как написать знак рубля на клавиатуре windows 10
  • Как нарезать образ windows на флешку ultraiso

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии