Уроки Windows Forms C++/C#
Калькулятор в Windovs Forms MVS C++В этом уроке представлена реализация, пожалуй, одной из самых популярных программ, которой каждый день пользуется огромное количество людей. В одном из "уроков C++" рассматривался калькулятор на примере элемента выбора "switch: case". В этом проекте будут кнопки, обозначающие отдельные вычисления, так же, по мимо этого, будет присутствовать форма, на которой будут расположены кнопки, обозначающие какие-либо действия, которые мы опишем в коде. Для этого нам понадобятся: 9 “button”, 1 "label", 1 "PictureBox" и 3 "textbox" – в 1-ый и 2-й “textBox”ы пользователь будет записывать числа, затем нажимать кнопку действия, после чего в 3-ем "textBox" будет показан результат вычислений. Калькулятор будет выполнять все стандартные действия: сложение, вычитание, умножение, деление, возведение в степень, которую надо ввести самому, тем сам можно извлекать корень числа, написав во втором "textBox", например, 0,333 (кубический корень). Помимо этого калькулятор будет вычислять синус, косинус, тангенс и катангенс, если вы хотите чтобы он ещё вычислял арккосинус, арксинус и т.д, можете так же описать их – эти действия рассматриваются в "уроках C++". Теперь приступим к оформлению программы:

В "PictureBox" можно вставить, вот такую картинку:

О том как вставлять картинку в “PictureBox”, рассказывается в “’этом уроке”. Но картинка будет большой и не помещаться! Оставьте размер “PictureBox”,как и был, а в “Form1_Load” напишите: this->pictureBox1->SizeMode = PictureBoxSizeMode::StretchImage; После этого размер, загружаемой, картинки будет равен размеру “PictureBox”. По мимо этого нужно будет подключить библиотеку - #include "math.h" в самом верху кода, если не знаете как, то вы можете посмотреть это в предыдущем уроке. Так же картинку можно загружать программно – кодом, это подробно рассматривается в этом уроке. И здесь так же вызываем событие "KeyPress" у всех “textBox”ов по очереди. Если не знаете, как вызвать событие у элемента, то посмотрите “этот урок”. Что бы размер формы был фиксирован – нажмите на неё и выберите свойство: "FormBorderStyles"->"Fixed3D". Теперь приступим к коду программы, вот он:
C++
#pragma endregion String^ TorZ; private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) { this->Text = "Калькулятор"; pictureBox1->Image=Image::FromFile("d:\\12.0.jpeg"); this->pictureBox1->SizeMode = PictureBoxSizeMode::StretchImage; label1->Text = "Равно:"; button1->Text = "+"; button2->Text = "-"; button3->Text = "*"; button4->Text = "/"; button5->Text = "pow"; button6->Text = "sin"; button7->Text = "cos"; button8->Text = "tan"; button9->Text = "ctan"; TorZ = Globalization::NumberFormatInfo::CurrentInfo->NumberDecimalSeparator; } private: System::Void textBox1_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) { bool TZFound = false; if (Char::IsDigit(e->KeyChar) == true) return; if (e->KeyChar == (char)Keys::Back) return; if (textBox1->Text->IndexOf(TorZ) != -1) TZFound = true; if (TZFound == true) { e->Handled = true; return; } if (e->KeyChar.ToString() == TorZ) return; e->Handled = true; } private: System::Void textBox2_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) { bool TZFound = false; if (Char::IsDigit(e->KeyChar) == true) return; if (e->KeyChar == (char)Keys::Back) return; if (textBox2->Text->IndexOf(TorZ) != -1) TZFound = true; if (TZFound == true) { e->Handled = true; return; } if (e->KeyChar.ToString() == TorZ) return; e->Handled = true; } private: System::Void textBox3_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) { bool TZFound = false; if (Char::IsDigit(e->KeyChar) == true) return; if (e->KeyChar == (char)Keys::Back) return; if (textBox3->Text->IndexOf(TorZ) != -1) TZFound = true; if (TZFound == true) { e->Handled = true; return; } if (e->KeyChar.ToString() == TorZ) return; e->Handled = true; } private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) { Single a, b, c = 0; Single A = Single::TryParse(textBox1->Text, System::Globalization::NumberStyles::Number, System::Globalization::NumberFormatInfo::CurrentInfo, a); Single B = Single::TryParse(textBox2->Text, System::Globalization::NumberStyles::Number, System::Globalization::NumberFormatInfo::CurrentInfo, b); c = a + b; textBox3->Text = String::Format("{0:F4}", c); } private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) { Single a, b, c = 0; Single A = Single::TryParse(textBox1->Text, System::Globalization::NumberStyles::Number, System::Globalization::NumberFormatInfo::CurrentInfo, a); Single B = Single::TryParse(textBox2->Text, System::Globalization::NumberStyles::Number, System::Globalization::NumberFormatInfo::CurrentInfo, b); c = a - b; textBox3->Text = String::Format("{0:F4}", c); } private: System::Void button3_Click(System::Object^ sender, System::EventArgs^ e) { Single a, b, c = 0; Single A = Single::TryParse(textBox1->Text, System::Globalization::NumberStyles::Number, System::Globalization::NumberFormatInfo::CurrentInfo, a); Single B = Single::TryParse(textBox2->Text, System::Globalization::NumberStyles::Number, System::Globalization::NumberFormatInfo::CurrentInfo, b); c = a * b; textBox3->Text = String::Format("{0:F4}", c); } private: System::Void button4_Click(System::Object^ sender, System::EventArgs^ e) { Single a, b, c = 0; Single A = Single::TryParse(textBox1->Text, System::Globalization::NumberStyles::Number, System::Globalization::NumberFormatInfo::CurrentInfo, a); Single B = Single::TryParse(textBox2->Text, System::Globalization::NumberStyles::Number, System::Globalization::NumberFormatInfo::CurrentInfo, b); c = a / b; textBox3->Text = String::Format("{0:F4}", c); } private: System::Void button5_Click(System::Object^ sender, System::EventArgs^ e) { Single a, b, c = 0; Single A = Single::TryParse(textBox1->Text, System::Globalization::NumberStyles::Number, System::Globalization::NumberFormatInfo::CurrentInfo, a); Single B = Single::TryParse(textBox2->Text, System::Globalization::NumberStyles::Number, System::Globalization::NumberFormatInfo::CurrentInfo, b); c = pow(a,b); // возвести a в степень b textBox3->Text = String::Format("{0:F4}", c); } private: System::Void button6_Click(System::Object^ sender, System::EventArgs^ e) { Single a, b, c = 0, d = 0; Single A = Single::TryParse(textBox1->Text, System::Globalization::NumberStyles::Number, System::Globalization::NumberFormatInfo::CurrentInfo, a); Single B = Single::TryParse(textBox2->Text, System::Globalization::NumberStyles::Number, System::Globalization::NumberFormatInfo::CurrentInfo, b); c = sin(a*3.14/180); d = sin(b*3.14/180); // Если поле textBox пусто, то результатом будет 1 textBox3->Text = String::Format("{0:F2} | {1:F2}", c, d); } private: System::Void button7_Click(System::Object^ sender, System::EventArgs^ e) { Single a, b, c = 0, d = 0; Single A = Single::TryParse(textBox1->Text, System::Globalization::NumberStyles::Number, System::Globalization::NumberFormatInfo::CurrentInfo, a); Single B = Single::TryParse(textBox2->Text, System::Globalization::NumberStyles::Number, System::Globalization::NumberFormatInfo::CurrentInfo, b); c = cos(a*3.14/180); d = cos(b*3.14/180); // Если поле textBox пусто, то результатом будет 1 textBox3->Text = String::Format("{0:F2} | {1:F2}", c, d); } private: System::Void button8_Click(System::Object^ sender, System::EventArgs^ e) { Single a, b, c = 0, d = 0; Single A = Single::TryParse(textBox1->Text, System::Globalization::NumberStyles::Number, System::Globalization::NumberFormatInfo::CurrentInfo, a); Single B = Single::TryParse(textBox2->Text, System::Globalization::NumberStyles::Number, System::Globalization::NumberFormatInfo::CurrentInfo, b); c = tan(a*3.14/180); d = tan(b*3.14/180); // Если поле textBox пусто, то результатом будет 1 textBox3->Text = String::Format("{0:F2} | {1:F2}", c, d); } private: System::Void button9_Click(System::Object^ sender, System::EventArgs^ e) { Single a, b, c = 0, d = 0; Single A = Single::TryParse(textBox1->Text, System::Globalization::NumberStyles::Number, System::Globalization::NumberFormatInfo::CurrentInfo, a); Single B = Single::TryParse(textBox2->Text, System::Globalization::NumberStyles::Number, System::Globalization::NumberFormatInfo::CurrentInfo, b); c = 1/tan(a*3.14/180); d = 1/tan(b*3.14/180); // Если поле textBox пусто, то результатом будет 1 textBox3->Text = String::Format("{0:F2} | {1:F2}", c, d); } }; }
Результат:
Следующий урок >>