C#

2020.08.20(목) - C# 윈폼 & C#

J_Bin 2020. 8. 20. 18:24

- 입사 후 3~5년 까지는 일을 빨리하고 일을 많이 달라고 해라

 

 

 

 

 

* MaskedTextBox

(입력되는 형식을 제한할 수 있다.)

 

- Form1.cs[디자인]

 

-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.Threading.Tasks;
using System.Windows.Forms;

namespace _2020._08._20_001
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string str;

            str = "입사일 : " + maskedTextBox1.Text + "\n";
            str += "우편번호 : " + maskedTextBox2.Text + "\n";
            str += "주소 : " + textBox1.Text + "\n";
            str += "휴대폰 번호 : " + maskedTextBox3.Text + "\n";
            str += "주민등록번호 : " + maskedTextBox4.Text + "\n";
            str += "이메일 : " + textBox2.Text + "\n";


            MessageBox.Show(str, "개인정보");

        }
    }
}

- 결과

 

* 콤보박스를 이용한 학점계산기

 

-Form1.cs[디자인]

 

 

-Form1.cs

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

namespace _2020._08._20_002
{
    public partial class Form1 : Form
    {
        TextBox[] titles;       // 교과목
        ComboBox[] crds;        // 학점
        ComboBox[] grds;        // 성적

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            textBox1.Text = "인제의 구조와 기능";
            textBox2.Text = "일반수학";
            textBox3.Text = "디지털공학및실험";
            textBox4.Text = "자료구조";
            textBox5.Text = "비주얼프로그래밍";
            textBox6.Text = "기업가정신";

            crds = new ComboBox[] { comboBox1, comboBox2, comboBox3, comboBox4, comboBox5, comboBox6, comboBox7 };
            grds = new ComboBox[] { comboBox8, comboBox9, comboBox10, comboBox11, comboBox12, comboBox13, comboBox14 };
            titles = new TextBox[] { textBox1, textBox2, textBox3, textBox4, textBox5, textBox6, textBox7 };

            int[] arrCredit = { 1, 2, 3, 4, 5 };        // 학점 콤보박스에 표시될 Item들
            List<String> lstGrade = new List<string>    // 성적 콤보박스에 표시될 Item들
            { "A+","A0","B+","B0","C+","C0","D+","D0","F"};

            foreach (var combo in crds)      // 학점 콤보박스 표현하기
            {
                foreach (var i in arrCredit)    
                {
                    combo.Items.Add(i);     // crds의 각 combobox에 arrCredit의 i 값들을 넣어라!
                }
                //combo.SelectedItem = 3;     // 학점 콤보박스 처음에 표시되는 숫자
            }

            foreach (var gr in grds)        // 성적 콤보박스 표현하기
            {
                foreach (var gritem in lstGrade)    // grds의 콤보박스에 lstGrade 값 넣기
                {
                    gr.Items.Add(gritem);           // gr의 Items에 gritem 넣기
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            double totalScore = 0;      // 총 점수
            int totalCredit = 0;        // 총 학점


            for (int i = 0; i < crds.Length; i++)   // 학점 콤보박스의 길이에 따라 
            {
                if (titles[i].Text != "")           // title 값이 i에 따라 증가하는데 text가 채워져있으면?
                {
                    int crd = int.Parse(crds[i].SelectedItem.ToString());       // crds의 선택된 값들을 string화 해서 다시 int화 한 다음 crd에 대입
                    totalCredit = totalCredit + crd;
                    totalScore += crd * GetGrade(grds[i].SelectedItem.ToString());
                }
                textBox9.Text = (totalScore / totalCredit).ToString("0.00");
            }
        }

        private double GetGrade(string text)
        {

            double grade = 0;

            if (text == "A+")
            {
                grade = 4.5;
            }
            else if (text == "A0") grade = 4.0;
            else if (text == "B+") grade = 3.5;
            else if (text == "B0") grade = 3.0;
            else if (text == "C+") grade = 2.5;
            else if (text == "C0") grade = 2.0;
            else if (text == "D+") grade = 1.5;
            else if (text == "D0") grade = 1.0;
            else grade = 0;
            return grade;


        }
    }
}

 

- 결과

 

* Timer 컨트롤을 이용한 디지털 시계

- 컴퓨터는 상대적으로 시간을 계산한다.

 

-Form1.cs[디자인]

 

- 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.Threading.Tasks;
using System.Windows.Forms;

namespace _2020._08._20_003
{
    public partial class Form1 : Form
    {
        private int CountMS = 0;        //밀리초
        private int CountM = 0;         //분
        private int CountS = 0;         //초
        private bool Toggle = false;    //Toggle은 반대되는 의미를 뜻함
        public Form1()
        {
            InitializeComponent();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {   
            // 숫자계산을 담당하는 애
            ++CountMS;
            // 1/100초가 100이되어야 1초이다.
            if (CountMS == 50)
            {
                CountMS = 0;
                ++CountS;
                if (CountS == 70)
                {
                    CountS = 0;
                    ++CountM;
                }
            }

        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            // 화면에 띄우는 것을 담당하는 애

            DispM.Text = CountM.ToString();

            DispS.Text = CountS.ToString();

            DispMS.Text = CountMS.ToString();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (Toggle == false)
            {
                timer1.Start();
                timer2.Start();
                Toggle = true;
            }
            else
            {
                timer1.Stop();
                timer2.Stop();
                Toggle = false;
            }
           



        }

        private void button2_Click(object sender, EventArgs e)
        {
            timer1.Stop();
            timer2.Stop();
            Toggle = false;

            CountM = 0;
            CountS = 0;
            CountMS = 0;

            DispM.Text = CountM.ToString();

            DispS.Text = CountS.ToString();

            DispMS.Text = CountMS.ToString();
        }
    }
}

- 결과

 

* TabControl을 사용한 디지털 알람시계

 

- Form1.cs[디자인]

 

- 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.Threading.Tasks;
using System.Windows.Forms;

namespace _2020._08._20_005
{
    public partial class Form1 : Form
    {
        // 변수설정

        private Timer myTimer = new Timer();
        private DateTime dDay;
        private DateTime tTime;
        private bool setAlarm;

        public Form1()
        {
            InitializeComponent();

            // 색상변경
            lblAlarm.ForeColor = Color.Gray;
            lblAlarmSet.ForeColor = Color.Gray;

            // timepicker 설정
            timePicker.Format = DateTimePickerFormat.Custom;
            timePicker.CustomFormat = "tt hh:mm";

            myTimer.Interval = 1000;
            myTimer.Tick += MyTimer_Tick;
            myTimer.Start();

            tabControl1.SelectedTab = tabPage2;
        }

        private void MyTimer_Tick(object sender, EventArgs e)
        {
            DateTime cTime = DateTime.Now;
            // 현재날짜와 현재시각을 표현해준다.
            lblDate.Text = cTime.ToShortDateString();
            lblTime.Text = cTime.ToShortTimeString();

            if (setAlarm == true)
            {
                if (dDay == DateTime.Today && cTime.Hour == tTime.Hour && cTime.Minute == tTime.Minute)
                {
                    setAlarm = false;
                    MessageBox.Show("Alarm!");
                }
            }
        }

        private void btnSet_Click(object sender, EventArgs e)
        {
            dDay = DateTime.Parse(datePicker.Text);
            tTime = DateTime.Parse(datePicker.Text);

            setAlarm = true;
            lblAlarmSet.ForeColor = Color.Red;
            lblAlarm.ForeColor = Color.Blue;
            lblAlarm.Text = "Alarm : " + dDay.ToShortDateString() + " " + tTime.ToLongTimeString();
            tabControl1.SelectedTab = tabPage2;
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            setAlarm = false;
            lblAlarmSet.ForeColor = Color.Gray;
            lblAlarm.ForeColor = Color.Gray;
            lblAlarm.Text = "Alarm : ";
            tabControl1.SelectedTab = tabPage2;

        }
    }
}

 

- 결과

 

 

* Random 클래스

 

- 소스코드

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _2020._08._20_006
{
    class Program
    {
        static void Main(string[] args)
        {
            Random r = new Random();
            Console.Write("{0,-16}", "Random Bytes");
            Byte[] b = new byte[5];
            r.NextBytes(b);

            foreach (var x in b)
            {   // 12자리로 출력
                Console.Write("{0,12}", x);
            }
            Console.WriteLine();

            // 5개 double 랜덤값 생성
            Console.Write("{0,-16}", "Random Double");
            double[] d = new double[5];

            for (int i = 0; i < d.Length; i++)
            {
                d[i] = r.NextDouble();
            }
            foreach (var x in d)
            {   // 12자리, 소수점 아래로 8자리 출력
                Console.Write("{0,12:F8}", x);
            }
            Console.WriteLine();


            // 5개 int 랜덤값 생성
            Console.Write("{0,-16}", "Random Int32");
            int[] a = new int[5];

            for (int i = 0; i < a.Length; i++)
            {
                a[i] = r.Next();
            }
            PrintArray(a);

            // 0~99까지의 랜덤 int
            Console.Write("{0,-16}", "Random 0~99");
            int[] v = new int[5];

            for (int i = 0; i < v.Length; i++)
            {
                v[i] = r.Next(100);
            }
            PrintArray(v);
        }

        private static void PrintArray(int[] v)
        {
            foreach (var value in v)
            {   // v 배열의 value들을 12자리로 출력하는 메서드
                Console.Write("{0,12}", value);
            }
            Console.WriteLine();
        }
    }
}

 

- 결과

Random 클래스는 빌드 할 때마다 랜덤으로 값을 불러오기 때문에 출력되는 값이 다 다르다.

 

* 숫자 야구게임 만들기(Random 클래스 이용)

 

- Form1.cs[디자인]

 

- 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.Threading.Tasks;
using System.Windows.Forms;

namespace _2020._08._20_007
{
    public partial class Form1 : Form
    {
        int[] intArray;
        public Form1()
        {
            InitializeComponent();

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Random aRandom = new Random();
            // intArray 초기화
            intArray = new int[3] { 100, 100, 100 };

            for (int Count = 0; Count < intArray.Length ; ++Count)      // Count : 랜덤 숫자를 저장할 곳
            {
                int iTemp = aRandom.Next(0,10);
                //MessageBox.Show("생성 : " + iTemp.ToString());
                int Count2;
                for (Count2 = 0; Count2 < intArray.Length; ++Count2)    // Count2 : 생성된 랜덤 숫자가 겹치는지 곳
                {
                    if (iTemp == intArray[Count2])  // 생성된 랜덤 숫자가 겹치면?
                    {
                        //MessageBox.Show("겹침 : " + iTemp.ToString());
                        break;
                    }
                }
                if (Count2 < intArray.Length)   // 숫자가 겹쳤다.
                {
                    --Count;
                    continue;
                }
                intArray[Count] = iTemp;
            }
            lbRand1.Text = intArray[0].ToString();
            lbRand2.Text = intArray[1].ToString();
            lbRand3.Text = intArray[2].ToString();



        }

        private void button1_Click(object sender, EventArgs e)
        {
            int[] InputArray = new int[intArray.Length];
            InputArray[0] = Convert.ToInt32(txtinput1.Text);
            InputArray[1] = int.Parse(txtinput2.Text);
            InputArray[2] = int.Parse(txtinput3.Text);

        }
    }
}