반응형

전체 소스는 https://github.com/msab2170/SimpleCalculator 에서 확인하실 수 있습니다.

 

GitHub - msab2170/SimpleCalculator

Contribute to msab2170/SimpleCalculator development by creating an account on GitHub.

github.com

계산기 파일은... 아직 인증서 관련 공부가 되지않아서 흑흑...... 추후에 가능하면 올릴게용

 

 

visual studio 2022를 설치하고 windows form로 새 프로젝트를 엽니다.

 

1. 도구상자를 열면 다양한 도구들을 검색할 수 있다.

 

2. 그중에서 tableLayoutPanel로 계산기 버튼 윤곽을 만들고

(초기 2x2 인데 행추가 열추가로 만들어주면 됩니다.

저와 동일하게 한다면 4x4까지,

크기가 균등하지 않을텐데 

tableLayoutPanel 좌측 상단의 사방 화살표를 우클리갛면 아래와 같이 나오고

"행 및 열 편집..."에 들어가서 %로 25%씩(4x4기준) 해주면 고르게 나뉘어집니다.)

그리고 계산 식과 결과가 나올 자리에는 kotlin에서 input 처럼 label이라는 도구를 검색하여 적어줍니다.

 

참고로 버튼과 label의 보이는 값은 도구 속성중 "text"를 찾으시면되고 각 컴포넌트들의 이름은 (name)에 해당합니다.

이제 디자인은 완성되었고 cs파일로 넘어가서 코딩하는데 저는 이미 완성이 되었기 때문에 코드 전문을 붙여 넣고 설명 드릴게요.

 

먼저 디자인을 완성하면 .Designer.cs 로 끝나는 파일에 다음과 같은 소스가 들어갑니다.

각 위치와 (name), text에 맞게 자동으로 코딩이 되고, 초기 디자인 화면에서 각 버튼을 더블클릭하면

.cs로 끝나는 파일에 자동으로 함수가 설정되기도합니다.

 

-- 아래 코드는 자동으로 설정되므로 오류가 난 경우나 필자가 의도한 이상의 부분을 건드리고 싶은 것이 아니라면

보기만 하고 넘어갑니다!

(대충 각 레이아웃, 버튼들의 위치, 사이즈 등을 지정해둔 것)

 

적당히 보시면서 쭈욱 밑으로 오시면 되겠습니다.

namespace WindowsFormsApp1
{
    partial class Form1
    {
        /// <summary>
        /// 필수 디자이너 변수입니다.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 사용 중인 모든 리소스를 정리합니다.
        /// </summary>
        /// <param name="disposing">관리되는 리소스를 삭제해야 하면 true이고, 그렇지 않으면 false입니다.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form 디자이너에서 생성한 코드

        /// <summary>
        /// 디자이너 지원에 필요한 메서드입니다. 
        /// 이 메서드의 내용을 코드 편집기로 수정하지 마세요.
        /// </summary>
        private void InitializeComponent()
        {
            this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
            this.btnPlus = new System.Windows.Forms.Button();
            this.btnEnter = new System.Windows.Forms.Button();
            this.btn0 = new System.Windows.Forms.Button();
            this.btnReset = new System.Windows.Forms.Button();
            this.btnMinus = new System.Windows.Forms.Button();
            this.btn3 = new System.Windows.Forms.Button();
            this.btn2 = new System.Windows.Forms.Button();
            this.btn1 = new System.Windows.Forms.Button();
            this.btnMultiply = new System.Windows.Forms.Button();
            this.btn6 = new System.Windows.Forms.Button();
            this.btn5 = new System.Windows.Forms.Button();
            this.btn4 = new System.Windows.Forms.Button();
            this.btnDivide = new System.Windows.Forms.Button();
            this.btn9 = new System.Windows.Forms.Button();
            this.btn8 = new System.Windows.Forms.Button();
            this.btn7 = new System.Windows.Forms.Button();
            this.result = new System.Windows.Forms.Label();
            this.tableLayoutPanel1.SuspendLayout();
            this.SuspendLayout();
            // 
            // tableLayoutPanel1
            // 
            this.tableLayoutPanel1.AutoSize = true;
            this.tableLayoutPanel1.ColumnCount = 4;
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
            this.tableLayoutPanel1.Controls.Add(this.btnPlus, 3, 3);
            this.tableLayoutPanel1.Controls.Add(this.btnEnter, 2, 3);
            this.tableLayoutPanel1.Controls.Add(this.btn0, 1, 3);
            this.tableLayoutPanel1.Controls.Add(this.btnReset, 0, 3);
            this.tableLayoutPanel1.Controls.Add(this.btnMinus, 3, 2);
            this.tableLayoutPanel1.Controls.Add(this.btn3, 2, 2);
            this.tableLayoutPanel1.Controls.Add(this.btn2, 1, 2);
            this.tableLayoutPanel1.Controls.Add(this.btn1, 0, 2);
            this.tableLayoutPanel1.Controls.Add(this.btnMultiply, 3, 1);
            this.tableLayoutPanel1.Controls.Add(this.btn6, 2, 1);
            this.tableLayoutPanel1.Controls.Add(this.btn5, 1, 1);
            this.tableLayoutPanel1.Controls.Add(this.btn4, 0, 1);
            this.tableLayoutPanel1.Controls.Add(this.btnDivide, 3, 0);
            this.tableLayoutPanel1.Controls.Add(this.btn9, 2, 0);
            this.tableLayoutPanel1.Controls.Add(this.btn8, 1, 0);
            this.tableLayoutPanel1.Controls.Add(this.btn7, 0, 0);
            this.tableLayoutPanel1.Location = new System.Drawing.Point(12, 94);
            this.tableLayoutPanel1.Name = "tableLayoutPanel1";
            this.tableLayoutPanel1.RowCount = 4;
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 25F));
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 25F));
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 25F));
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 25F));
            this.tableLayoutPanel1.Size = new System.Drawing.Size(776, 352);
            this.tableLayoutPanel1.TabIndex = 0;
            this.tableLayoutPanel1.Paint += new System.Windows.Forms.PaintEventHandler(this.tableLayoutPanel1_Paint);
            // 
            // btnPlus
            // 
            this.btnPlus.AutoSize = true;
            this.btnPlus.Font = new System.Drawing.Font("굴림", 15F);
            this.btnPlus.Location = new System.Drawing.Point(585, 267);
            this.btnPlus.Name = "btnPlus";
            this.btnPlus.Size = new System.Drawing.Size(188, 82);
            this.btnPlus.TabIndex = 15;
            this.btnPlus.Text = "+";
            this.btnPlus.UseVisualStyleBackColor = true;
            this.btnPlus.Click += new System.EventHandler(this.btnPlus_Click);
            // 
            // btnEnter
            // 
            this.btnEnter.AutoSize = true;
            this.btnEnter.Font = new System.Drawing.Font("굴림", 15F);
            this.btnEnter.Location = new System.Drawing.Point(391, 267);
            this.btnEnter.Name = "btnEnter";
            this.btnEnter.Size = new System.Drawing.Size(188, 82);
            this.btnEnter.TabIndex = 14;
            this.btnEnter.Text = "=";
            this.btnEnter.UseVisualStyleBackColor = true;
            this.btnEnter.Click += new System.EventHandler(this.btnEnter_Click);
            // 
            // btn0
            // 
            this.btn0.AutoSize = true;
            this.btn0.Font = new System.Drawing.Font("굴림", 15F);
            this.btn0.Location = new System.Drawing.Point(197, 267);
            this.btn0.Name = "btn0";
            this.btn0.Size = new System.Drawing.Size(188, 82);
            this.btn0.TabIndex = 13;
            this.btn0.Text = "0";
            this.btn0.UseVisualStyleBackColor = true;
            this.btn0.Click += new System.EventHandler(this.btn0_Click);
            // 
            // btnReset
            // 
            this.btnReset.AutoSize = true;
            this.btnReset.Font = new System.Drawing.Font("굴림", 15F);
            this.btnReset.Location = new System.Drawing.Point(3, 267);
            this.btnReset.Name = "btnReset";
            this.btnReset.Size = new System.Drawing.Size(188, 82);
            this.btnReset.TabIndex = 12;
            this.btnReset.Text = "AC";
            this.btnReset.UseVisualStyleBackColor = true;
            this.btnReset.Click += new System.EventHandler(this.btnReset_Click);
            // 
            // btnMinus
            // 
            this.btnMinus.AutoSize = true;
            this.btnMinus.Font = new System.Drawing.Font("굴림", 15F);
            this.btnMinus.Location = new System.Drawing.Point(585, 179);
            this.btnMinus.Name = "btnMinus";
            this.btnMinus.Size = new System.Drawing.Size(188, 82);
            this.btnMinus.TabIndex = 11;
            this.btnMinus.Text = "-";
            this.btnMinus.UseVisualStyleBackColor = true;
            this.btnMinus.Click += new System.EventHandler(this.btnMinus_Click);
            // 
            // btn3
            // 
            this.btn3.AutoSize = true;
            this.btn3.Font = new System.Drawing.Font("굴림", 15F);
            this.btn3.Location = new System.Drawing.Point(391, 179);
            this.btn3.Name = "btn3";
            this.btn3.Size = new System.Drawing.Size(188, 82);
            this.btn3.TabIndex = 10;
            this.btn3.Text = "3";
            this.btn3.UseVisualStyleBackColor = true;
            this.btn3.Click += new System.EventHandler(this.btn3_Click);
            // 
            // btn2
            // 
            this.btn2.AutoSize = true;
            this.btn2.Font = new System.Drawing.Font("굴림", 15F);
            this.btn2.Location = new System.Drawing.Point(197, 179);
            this.btn2.Name = "btn2";
            this.btn2.Size = new System.Drawing.Size(188, 82);
            this.btn2.TabIndex = 9;
            this.btn2.Text = "2";
            this.btn2.UseVisualStyleBackColor = true;
            this.btn2.Click += new System.EventHandler(this.btn2_Click);
            // 
            // btn1
            // 
            this.btn1.AutoSize = true;
            this.btn1.Font = new System.Drawing.Font("굴림", 15F);
            this.btn1.Location = new System.Drawing.Point(3, 179);
            this.btn1.Name = "btn1";
            this.btn1.Size = new System.Drawing.Size(188, 82);
            this.btn1.TabIndex = 8;
            this.btn1.Text = "1";
            this.btn1.UseVisualStyleBackColor = true;
            this.btn1.Click += new System.EventHandler(this.btn1_Click);
            // 
            // btnMultiply
            // 
            this.btnMultiply.AutoSize = true;
            this.btnMultiply.Font = new System.Drawing.Font("굴림", 15F);
            this.btnMultiply.Location = new System.Drawing.Point(585, 91);
            this.btnMultiply.Name = "btnMultiply";
            this.btnMultiply.Size = new System.Drawing.Size(188, 82);
            this.btnMultiply.TabIndex = 7;
            this.btnMultiply.Text = "X";
            this.btnMultiply.UseVisualStyleBackColor = true;
            this.btnMultiply.Click += new System.EventHandler(this.btnMultiply_Click);
            // 
            // btn6
            // 
            this.btn6.AutoSize = true;
            this.btn6.Font = new System.Drawing.Font("굴림", 15F);
            this.btn6.Location = new System.Drawing.Point(391, 91);
            this.btn6.Name = "btn6";
            this.btn6.Size = new System.Drawing.Size(188, 82);
            this.btn6.TabIndex = 6;
            this.btn6.Text = "6";
            this.btn6.UseVisualStyleBackColor = true;
            this.btn6.Click += new System.EventHandler(this.btn6_Click);
            // 
            // btn5
            // 
            this.btn5.AutoSize = true;
            this.btn5.Font = new System.Drawing.Font("굴림", 15F);
            this.btn5.Location = new System.Drawing.Point(197, 91);
            this.btn5.Name = "btn5";
            this.btn5.Size = new System.Drawing.Size(188, 82);
            this.btn5.TabIndex = 5;
            this.btn5.Text = "5";
            this.btn5.UseVisualStyleBackColor = true;
            this.btn5.Click += new System.EventHandler(this.btn5_Click);
            // 
            // btn4
            // 
            this.btn4.AutoSize = true;
            this.btn4.Font = new System.Drawing.Font("굴림", 15F);
            this.btn4.Location = new System.Drawing.Point(3, 91);
            this.btn4.Name = "btn4";
            this.btn4.Size = new System.Drawing.Size(188, 82);
            this.btn4.TabIndex = 4;
            this.btn4.Text = "4";
            this.btn4.UseVisualStyleBackColor = true;
            this.btn4.Click += new System.EventHandler(this.btn4_Click);
            // 
            // btnDivide
            // 
            this.btnDivide.AutoSize = true;
            this.btnDivide.Font = new System.Drawing.Font("굴림", 15F);
            this.btnDivide.Location = new System.Drawing.Point(585, 3);
            this.btnDivide.Name = "btnDivide";
            this.btnDivide.Size = new System.Drawing.Size(188, 82);
            this.btnDivide.TabIndex = 3;
            this.btnDivide.Text = "/";
            this.btnDivide.UseVisualStyleBackColor = true;
            this.btnDivide.Click += new System.EventHandler(this.btnDivide_Click);
            // 
            // btn9
            // 
            this.btn9.AutoSize = true;
            this.btn9.Font = new System.Drawing.Font("굴림", 15F);
            this.btn9.Location = new System.Drawing.Point(391, 3);
            this.btn9.Name = "btn9";
            this.btn9.Size = new System.Drawing.Size(188, 82);
            this.btn9.TabIndex = 2;
            this.btn9.Text = "9";
            this.btn9.UseVisualStyleBackColor = true;
            this.btn9.Click += new System.EventHandler(this.btn9_Click);
            // 
            // btn8
            // 
            this.btn8.AutoSize = true;
            this.btn8.Font = new System.Drawing.Font("굴림", 15F);
            this.btn8.Location = new System.Drawing.Point(197, 3);
            this.btn8.Name = "btn8";
            this.btn8.Size = new System.Drawing.Size(188, 82);
            this.btn8.TabIndex = 1;
            this.btn8.Text = "8";
            this.btn8.UseVisualStyleBackColor = true;
            this.btn8.Click += new System.EventHandler(this.btn8_Click);
            // 
            // btn7
            // 
            this.btn7.AutoSize = true;
            this.btn7.Font = new System.Drawing.Font("굴림", 15F);
            this.btn7.Location = new System.Drawing.Point(3, 3);
            this.btn7.Name = "btn7";
            this.btn7.Size = new System.Drawing.Size(188, 82);
            this.btn7.TabIndex = 0;
            this.btn7.Text = "7";
            this.btn7.UseVisualStyleBackColor = true;
            this.btn7.Click += new System.EventHandler(this.btn7_Click);
            // 
            // result
            // 
            this.result.BackColor = System.Drawing.SystemColors.HighlightText;
            this.result.Font = new System.Drawing.Font("굴림", 20F);
            this.result.Location = new System.Drawing.Point(12, 10);
            this.result.Name = "result";
            this.result.Padding = new System.Windows.Forms.Padding(5);
            this.result.Size = new System.Drawing.Size(773, 70);
            this.result.TabIndex = 1;
            this.result.Text = "0";
            this.result.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(808, 464);
            this.Controls.Add(this.result);
            this.Controls.Add(this.tableLayoutPanel1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.tableLayoutPanel1.ResumeLayout(false);
            this.tableLayoutPanel1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion
        private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
        private System.Windows.Forms.Button btn7;
        private System.Windows.Forms.Button btnPlus;
        private System.Windows.Forms.Button btnEnter;
        private System.Windows.Forms.Button btn0;
        private System.Windows.Forms.Button btnReset;
        private System.Windows.Forms.Button btnMinus;
        private System.Windows.Forms.Button btn3;
        private System.Windows.Forms.Button btn2;
        private System.Windows.Forms.Button btn1;
        private System.Windows.Forms.Button btnMultiply;
        private System.Windows.Forms.Button btn6;
        private System.Windows.Forms.Button btn5;
        private System.Windows.Forms.Button btn4;
        private System.Windows.Forms.Button btnDivide;
        private System.Windows.Forms.Button btn9;
        private System.Windows.Forms.Button btn8;
        private System.Windows.Forms.Label result;
    }
}

 

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

namespace WindowsFormsApp1
{
	// 앞에서 디자인한 Form을 응용프로그램 안에 적용하는 클래스입니다.
    // 앞에서 보실필요없다고 말씀은 드렸으나
    // 앞에서 보여드렸던 소스에 현재 페이지에서 특정버튼을 클릭하면 
    // 메소드를 실행시키도록 코딩되어있습니다.
    // 앞으로 가실필욘 없고 바로 하단에 간단한 예시를 들겠습니다.
    /* 예를들면 7 버튼의 경우
    	this.btn7.AutoSize = true;
        this.btn7.Font = new System.Drawing.Font("굴림", 15F);
        this.btn7.Location = new System.Drawing.Point(3, 3);
        this.btn7.Name = "btn7";
    	this.btn7.Size = new System.Drawing.Size(188, 82);
        this.btn7.TabIndex = 0;
        this.btn7.Text = "7";
        this.btn7.UseVisualStyleBackColor = true;
        
        this.btn7.Click += new System.EventHandler(this.btn7_Click); <--- 이자리에 
        이버튼이 클릭되면이라는 이벤트가 담겨있고 앞으로 
        개발할 btnX_Click()메소드가 이벤트로 들어가있죠.
    */
    
    public partial class Form1 : Form
    {
        bool afterEnter = false;
       
        public Form1()
        {
            InitializeComponent();
        }

        private void flowLayoutPanel1_Paint(object sender, PaintEventArgs e) { }
        private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e)  { }
  		
        // 설명드릴때는 어짜피 숫자들 버튼은 동일하므로 대표적으로 한개만 남기고 지워뒀습니다.
        
        private void btn1_Click(object sender, EventArgs e)
        {
        	// 가장 앞이 0인경우에는 0을 지운다.
            // afterEnter는 '=' 버튼을 누르고나면 true로 바뀌는 값으로 설정해두었습니다.
            // 다음계산시에 AC를 꼭 누르지않더라도 초기화 되도록 설계했습니다.
            
            if (result.Text.Equals("0") || afterEnter == true)  { result.Text = "1"; }      
            else { result.Text += 1; }
            afterEnter = false;
        }
		
         // 연산도 가장 간단하다고 판단한 방법으로 제일 밑줄만 다르므로 대표 하나만 남깁니다.
        private void btnMultiply_Click(object sender, EventArgs e)
        {
        	// 계산 시 0으로 나누면 "0으로 나눌 수 없습니다."로 표기하게끔 개발했기때문에
            // 해당 문구가 뜬 상태로 연산시 정상작동하기 위한 로직입니다.
             if(result.Text == "0으로 나눌 수 없습니다.")
            {
                result.Text = 0.ToString();
            }
            afterEnter = false;
            
            // a / b + c 식으로 연산자 두개를 붙이는 경우에는 계산이 안되는 로직이기 때문에
            // 이미 연산자가 있을때 추가 연산자가 들어오면 앞의 계산을 시행하도록 개발
            // 아주 간단한 계산기 예제 이기 때문에 괄호나 
            // +, - 보다 *, /가 먼저 계산되는 부분은 제외했습니다.
            
            if (result.Text.Contains(" "))
            {
                btnEnter_Click(sender, e);
                afterEnter = false;
            }
            result.Text += " * ";
        }
        
		// '=' 버튼을 눌렀을때 
        private void btnEnter_Click(object sender, EventArgs e)
        {
        	// 위의 버튼들 로직으로
            // ex) '15 + 4' 라는 값이 result.Text에 오게 됩니다.
            String temp = result.Text;
            
            // 연산자 없이 '='을 누르면 아무런 조치를 취하지 않음
            if (!temp.Contains(" ")) return;
             
            // 이를 Split으로 쪼개
            // {a, (연산자), b} 인 배열을 만들고
            // 각 연산을 수행하는 로직을 구성했습니다.
            // 단, 수학적으로 0으로 나누는 것은 불가능하기 때문에 예외처리를 해두었습니다.
            
            String[] arr = temp.Split(' ');
            int a = Int32.Parse(arr[0]);
            int b = Int32.Parse(arr[2]);
            afterEnter = true;
            if (arr[1] == "*")
            {
                result.Text = (a * b).ToString();
            } else if (arr[1] == "/") {
                if ( b == 0){
                    result.Text = "0으로 나눌 수 없습니다.";
                    afterEnter = true;
                } else {
                    result.Text = (a / b).ToString();
                }    
            } else if (arr[1] == "-"){
                result.Text = (a - b).ToString();
            } else if (arr[1] == "+"){
                result.Text = (a + b).ToString();
            }
        }

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

 

코틀린 배울때 모바일 화면 디자인하는 과정과 유사해서 무난하게 성공했어요! 완성!

 

반응형

+ Recent posts