반도체, 임베디드 Study/C#

C# - WinForm 연습 (Form, Button, CheckBox, ComboBox, GroupBox, Label, ListBox, TextBox, Timer... 구현 )

잇(IT) 2024. 6. 10. 18:09
728x90


전체 코드

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

namespace WindowsFormsApp3
{
    public partial class Form1 : Form
    {

        private string name1;
        private bool flag;
        string strmsg;
        string mspos;

        System.Timers.Timer swTimer;
        int h, m, s, ms;

        List<Point> ListPoint = new List<Point>();
        List<List<Point>> LListPoint = new List<List<Point>>();

        List<Point> Square = new List<Point>();
        List<List<Point>> SSquare = new List<List<Point>>();

        List<Point> tmpSquare = new List<Point>();

        int racCount = 0;
        //int squareCount = 0;

        //List<Point> rac = new List<Point> ();
        //List<Point> squ = new List<Point>();

        public Form1()
        {
            InitializeComponent();
            //- KeyPress 이벤트는 기본적으로 포커스가 있는 컨트롤(TextBox 등)에 의해 처리되기 때문에
            //- 폼 자체에서는 키보드 입력 이벤트가 발생하지 않을 수 있기 때문에 아래 코드를 추가한다.
            this.KeyPreview = true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //timer는 별도의 명령을 내려야 동작을 한다. default는 false이기 때문에 동작하지 않는다.
            timer1.Start();

            swTimer = new System.Timers.Timer();
            swTimer.Interval = 1;
            swTimer.Elapsed += OnTimeEvent;

            DialogResult mainResult = MessageBox.Show("WinForm을 실행하겠습니까?","Question", MessageBoxButtons.YesNo);

            if (mainResult == DialogResult.Yes)
            {
                return;
            }

            MessageBox.Show("타이틀을 갖는 메시지박스입니다.", "Title Messege");

            DialogResult result1 = MessageBox.Show("두개의 버튼을 갖는 메시지박스입니다.", "Question", MessageBoxButtons.YesNo);

            if (result1 == DialogResult.Yes)
            {
                MessageBox.Show("Yes를 입력했습니다.", "YesOrNo");
            }
            else if (result1 == DialogResult.No)
            {
                MessageBox.Show("No를 입력했습니다.", "YesOrNo");
            }

            DialogResult result2 = MessageBox.Show("세개의 버튼과 물음표 아이콘을 보여주는 메시지박스입니다.", "Question", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

            if (result2 == DialogResult.Yes)
            {
                MessageBox.Show("Yes를 입력했습니다.", "YesOrNoOrCancel");
            }
            else if (result2 == DialogResult.No)
            {
                MessageBox.Show("No를 입력했습니다.", "YesOrNoOrCancel");
            }
            else if (result2 == DialogResult.Cancel)
            {
                MessageBox.Show("Cancel를 입력했습니다.", "YesOrNoOrCancel");
            }
        }

        private void OnTimeEvent(object sender, ElapsedEventArgs e)
        {
            Invoke(new Action(() =>
            {
                ms += 1;
                if(ms == 100)
                {
                    ms = 0;
                    s += 1;
                }
                if (s == 60)
                {
                    s = 0;
                    m += 1;
                }
                if (m == 60)
                {
                    m = 0;
                    h += 1;
                }

                timer.Text = string.Format("{0}:{1}:{2}:{3}", h.ToString().PadLeft(2, '0'), m.ToString().PadLeft(2, '0'), s.ToString().PadLeft(2, '0'), ms.ToString().PadLeft(2, '0'));
            }));
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.DrawString("Test", Font, Brushes.Black, 30, 20);
            e.Graphics.DrawLine(Pens.Red, 10, 10, 100, 10);

            //- KeyPress용 코드
            //e.Graphics.DrawString(strmsg, Font, Brushes.Black, 20, 20);

            //Point 그리기
            //if(ListPoint.Count == 3)
            //{
            //    e.Graphics.DrawLine(Pens.Black, ListPoint[0], ListPoint[1]);
            //    e.Graphics.DrawLine(Pens.Black, ListPoint[0], ListPoint[2]);
            //    e.Graphics.DrawLine(Pens.Black, ListPoint[1], ListPoint[2]);
            //}

            //if(Square.Count == 4)
            //{
            //    e.Graphics.DrawLine(Pens.Black, Square[0], Square[1]);
            //    e.Graphics.DrawLine(Pens.Black, Square[0], Square[3]);
            //    e.Graphics.DrawLine(Pens.Black, Square[1], Square[2]);
            //    e.Graphics.DrawLine(Pens.Black, Square[2], Square[3]);
            //}

            //if(ListPoint.Count == 3)
            //{
            //    if(radioButton3.Enabled && radioButton3.Checked)
            //    {
            //        e.Graphics.DrawLine(Pens.Red, ListPoint[0], ListPoint[1]);
            //        e.Graphics.DrawLine(Pens.Red, ListPoint[0], ListPoint[2]);
            //        e.Graphics.DrawLine(Pens.Red, ListPoint[1], ListPoint[2]);
            //    }
            //    else if(radioButton4.Enabled && radioButton4.Checked)
            //    {
            //        e.Graphics.DrawLine(Pens.Green, ListPoint[0], ListPoint[1]);
            //        e.Graphics.DrawLine(Pens.Green, ListPoint[0], ListPoint[2]);
            //        e.Graphics.DrawLine(Pens.Green, ListPoint[1], ListPoint[2]);
            //    }
            //    else if(radioButton5.Enabled && radioButton5.Checked)
            //    {
            //        e.Graphics.DrawLine(Pens.Blue, ListPoint[0], ListPoint[1]);
            //        e.Graphics.DrawLine(Pens.Blue, ListPoint[0], ListPoint[2]);
            //        e.Graphics.DrawLine(Pens.Blue, ListPoint[1], ListPoint[2]);
            //    }
                
            //}

            //if(Square.Count == 4)
            //{
            //    if(radioButton3.Enabled && radioButton3.Checked)
            //    {
            //        e.Graphics.DrawLine(Pens.Red, Square[0], Square[1]);
            //        e.Graphics.DrawLine(Pens.Red, Square[0], Square[3]);
            //        e.Graphics.DrawLine(Pens.Red, Square[1], Square[2]);
            //        e.Graphics.DrawLine(Pens.Red, Square[2], Square[3]);
            //    }
            //    else if(radioButton4.Enabled && radioButton4.Checked)
            //    {
            //        e.Graphics.DrawLine(Pens.Green, Square[0], Square[1]);
            //        e.Graphics.DrawLine(Pens.Green, Square[0], Square[3]);
            //        e.Graphics.DrawLine(Pens.Green, Square[1], Square[2]);
            //        e.Graphics.DrawLine(Pens.Green, Square[2], Square[3]);
            //    }
            //    else if(radioButton5.Enabled && radioButton5.Checked)
            //    {
            //        e.Graphics.DrawLine(Pens.Blue, Square[0], Square[1]);
            //        e.Graphics.DrawLine(Pens.Blue, Square[0], Square[3]);
            //        e.Graphics.DrawLine(Pens.Blue, Square[1], Square[2]);
            //        e.Graphics.DrawLine(Pens.Blue, Square[2], Square[3]);
            //    }
            //}

            if(LListPoint.Count > 0)
            {
                for (int i = 0; i < LListPoint.Count; i++)
                {
                    Point firstPoint = LListPoint[i][0];
                    Point secondPoint = LListPoint[i][1];
                    Point thirdPoint = LListPoint[i][2];
                    e.Graphics.DrawLine(Pens.Black, firstPoint, secondPoint);
                    e.Graphics.DrawLine(Pens.Black, firstPoint, thirdPoint);
                    e.Graphics.DrawLine(Pens.Black, secondPoint, thirdPoint);
                }
            }

            if(SSquare.Count > 0)
            {
                for(int i= 0; i<SSquare.Count; i++)
                {
                    Point firstPoint = SSquare[i][0];
                    Point secondPoint = SSquare[i][1];
                    Point thirdPoint = SSquare[i][2];
                    Point fourthPoint = SSquare[i][3];
                    e.Graphics.DrawLine(Pens.Black, firstPoint, secondPoint);
                    e.Graphics.DrawLine(Pens.Black, firstPoint, fourthPoint);
                    e.Graphics.DrawLine(Pens.Black, secondPoint, thirdPoint);
                    e.Graphics.DrawLine(Pens.Black, thirdPoint, fourthPoint);
                }
            }
            
        }

        private void button3_Click(object sender, EventArgs e)
        {
            name_is.Text = $"{name1}이 입력되었습니다.";
        }

        private void NameBox_1_TextChanged(object sender, EventArgs e)
        {
            name1 = NameBox_1.Text;
        }

        //Interval 간격마다 해당 함수가 실행된다.
        private void timer1_Tick(object sender, EventArgs e)
        {
            flag = !flag;
            label2.Text = DateTime.Now.ToString();
            if (flag)
            {
                button1.BackColor = Color.White;
                button1.ForeColor = Color.Black; // 배경색이 흰색이면 글자색을 검정으로 설정
            }
            else
            {
                button1.BackColor = Color.Black;
                button1.ForeColor = Color.White; // 배경색이 검정이면 글자색을 흰색으로 설정
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            CheckBox[] checkBoxes = { checkBox1, checkBox2, checkBox3, checkBox4 };

            string summary = string.Empty;

            foreach(CheckBox checkBox in checkBoxes)
            {
                if(checkBox.Checked) summary += checkBox.Text + " ";
            }

            MessageBox.Show(summary, "결과 요약");
        }

        private void contry_SelectedIndexChanged(object sender, EventArgs e)
        {
            contryLabel.Text = contry.SelectedItem.ToString();
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            contry2.Text = listBox1.SelectedItem.ToString();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            timer1.Stop();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            timer1.Start();
        }

        private void Form1_KeyPress(object sender, KeyPressEventArgs e)
        {
            strmsg += e.KeyChar;
            label3.Text = strmsg;
            Invalidate();
        }

        private void swHour_Click(object sender, EventArgs e)
        {
            swTimer.Start();
        }

        private void swMin_Click(object sender, EventArgs e)
        {
            swTimer.Stop();
        }

        private void swSec_Click(object sender, EventArgs e)
        {
            swTimer.Stop();
            h = 0;
            m = 0;
            s = 0;
            ms = 0;
            timer.Text = "00:00:00";
        }

        private void Form1_MouseDoubleClick(object sender, MouseEventArgs e)
        {

            Point p = new Point(e.X, e.Y);

            if(Square.Count == 4)
            {
                Square.Clear();
            }
            Square.Add(p);
            Invalidate();
        }

        // - 그냥 삼각형, 사각형 그림 그리기
        //private void Form1_MouseDown(object sender, MouseEventArgs e)
        //{
        //    if(radioButton1.Enabled && radioButton1.Checked)
        //    {
        //        Point p = new Point(e.X, e.Y);

        //        if (ListPoint.Count == 3)
        //        {
        //            ListPoint.Clear();
        //        }
        //        ListPoint.Add(p);
        //        Invalidate();
        //    }

        //    if(radioButton2.Enabled && radioButton2.Checked)
        //    {
        //        Point p = new Point(e.X, e.Y);

        //        if (Square.Count == 4)
        //        {
        //            Square.Clear();
        //        }
        //        Square.Add(p);
        //        Invalidate();
        //    }
        //}

        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {

            
        }

        private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
            if (radioButton1.Enabled && radioButton1.Checked)
            {
                Point p = new Point(e.X, e.Y);

                if (ListPoint.Count > 0 && ListPoint.Count % 3 == 0)
                {
                    int lastPointIndexRac = ListPoint.Count - 1;
                    LListPoint.Add(make_rac_group(ListPoint[lastPointIndexRac - 2], ListPoint[lastPointIndexRac - 1], ListPoint[lastPointIndexRac]));
                }
                ListPoint.Add(p);
                Invalidate();
            }

            if (radioButton2.Enabled && radioButton2.Checked)
            {
                Point p = new Point(e.X, e.Y);

                if (Square.Count > 0 && Square.Count % 4 == 0)
                {
                    int lastPointIndexSquare = Square.Count - 1;
                    SSquare.Add(make_squ_group(Square[lastPointIndexSquare - 3], Square[lastPointIndexSquare - 2], Square[lastPointIndexSquare - 1], Square[lastPointIndexSquare]));
                }
                Square.Add(p);
                Invalidate();

            }
        }

        private void Form1_Click(object sender, EventArgs e)
        {

        }

        //-----------progressBar button
        private void button5_Click(object sender, EventArgs e)
        {
            timer2.Start();
        }

        //--------progressBar
        private void timer2_Tick(object sender, EventArgs e)
        {
            progressBar1.PerformStep();

            if(progressBar1.Value == 100)
            {
                timer1.Stop();
            }
            textBox1.Text = progressBar1.Value.ToString();
        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            mspos = $"(X,Y) = {e.X}, {e.Y}";
            label4.Text = mspos;
            Invalidate();
        }

        //private void Form1_Click(object sender, EventArgs e)
        //{
        //    MessageBox.Show("Click - 1");
        //}

        //private void Form1_MouseClick(object sender, MouseEventArgs e)
        //{
        //    MessageBox.Show("MouseClick - 1");
        //}

        //---------------------함수 생성
        private List<Point> make_rac_group(Point p1, Point p2, Point p3)
        {
            List<Point> tmprac = new List<Point>();
            tmprac.Add(p1);
            tmprac.Add(p2);
            tmprac.Add(p3);
            return tmprac;
        }

        private List<Point> make_squ_group(Point p1, Point p2, Point p3, Point p4)
        {
            List<Point> tmprac = new List<Point>();
            tmprac.Add(p1);
            tmprac.Add(p2);
            tmprac.Add(p3);
            tmprac.Add(p4);
            return tmprac;
        }
    }
}

(위 코드에서 삼각형을 그냥 그리는 것은 주석처리가 되어있고, 체크 박스에 따라 도형을 다르게 그리는 코드는 제대로 실행이 안되는 상태다 -> 추후에 수정할 예정이다.)


Form Load

Form Load 이벤트를 추가하여 WinForm이 실행되고 화면에 Form이 뜨기전 동작할 Action을 추가할 것이다.

private void Form1_Load(object sender, EventArgs e)
{

    DialogResult mainResult = MessageBox.Show("WinForm을 실행하겠습니까?","Question", MessageBoxButtons.YesNo);

    if (mainResult == DialogResult.Yes)
    {
        return;
    }

    MessageBox.Show("타이틀을 갖는 메시지박스입니다.", "Title Messege");

    DialogResult result1 = MessageBox.Show("두개의 버튼을 갖는 메시지박스입니다.", "Question", MessageBoxButtons.YesNo);

    if (result1 == DialogResult.Yes)
    {
        MessageBox.Show("Yes를 입력했습니다.", "YesOrNo");
    }
    else if (result1 == DialogResult.No)
    {
        MessageBox.Show("No를 입력했습니다.", "YesOrNo");
    }

    DialogResult result2 = MessageBox.Show("세개의 버튼과 물음표 아이콘을 보여주는 메시지박스입니다.", "Question", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

    if (result2 == DialogResult.Yes)
    {
        MessageBox.Show("Yes를 입력했습니다.", "YesOrNoOrCancel");
    }
    else if (result2 == DialogResult.No)
    {
        MessageBox.Show("No를 입력했습니다.", "YesOrNoOrCancel");
    }
    else if (result2 == DialogResult.Cancel)
    {
        MessageBox.Show("Cancel를 입력했습니다.", "YesOrNoOrCancel");
    }
}

 

위 코드는 Form_Load 이벤트를 통해 Winform이 실행될 때 MessageBox를 띄우는 코드다.

MessageBox의 Show 함수는 오버로드를 통해 파라미터에 따라 다르게 동작하게 구성되어 있다.

 

테스트를 위해 처음 MessageBox가 실행되고, YesNO 버튼을 통해 Yes가 입력될 경우 winform을 바로 실행하게 되고, No를 입력하게 될 경우 아래 if문들을 계속해서 실행된다.


 

Label, TextBox, Button을 이용한 입력값 출력하기

private void button3_Click(object sender, EventArgs e)
{
    name_is.Text = $"{name1}이 입력되었습니다.";
}

private void NameBox_1_TextChanged(object sender, EventArgs e)
{
    name1 = NameBox_1.Text;
}

List, Combo Box

private void contry_SelectedIndexChanged(object sender, EventArgs e)
{
    contryLabel.Text = contry.SelectedItem.ToString();
}

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    contry2.Text = listBox1.SelectedItem.ToString();
}

Clock

private void timer1_Tick(object sender, EventArgs e)
{
    flag = !flag;
    label2.Text = DateTime.Now.ToString();
    if (flag)
    {
        button1.BackColor = Color.White;
        button1.ForeColor = Color.Black; // 배경색이 흰색이면 글자색을 검정으로 설정
    }
    else
    {
        button1.BackColor = Color.Black;
        button1.ForeColor = Color.White; // 배경색이 검정이면 글자색을 흰색으로 설정
    }
}

Timer

private void OnTimeEvent(object sender, ElapsedEventArgs e)
{
    Invoke(new Action(() =>
    {
        ms += 1;
        if(ms == 100)
        {
            ms = 0;
            s += 1;
        }
        if (s == 60)
        {
            s = 0;
            m += 1;
        }
        if (m == 60)
        {
            m = 0;
            h += 1;
        }

        timer.Text = string.Format("{0}:{1}:{2}:{3}", h.ToString().PadLeft(2, '0'), m.ToString().PadLeft(2, '0'), s.ToString().PadLeft(2, '0'), ms.ToString().PadLeft(2, '0'));
    }));
    
private void swHour_Click(object sender, EventArgs e)
{
    swTimer.Start();
}

private void swMin_Click(object sender, EventArgs e)
{
    swTimer.Stop();
}

private void swSec_Click(object sender, EventArgs e)
{
    swTimer.Stop();
    h = 0;
    m = 0;
    s = 0;
    ms = 0;
    timer.Text = "00:00:00";
}

Check Box

private void button1_Click(object sender, EventArgs e)
{
    CheckBox[] checkBoxes = { checkBox1, checkBox2, checkBox3, checkBox4 };

    string summary = string.Empty;

    foreach(CheckBox checkBox in checkBoxes)
    {
        if(checkBox.Checked) summary += checkBox.Text + " ";
    }

    MessageBox.Show(summary, "결과 요약");
}

Cursor

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    mspos = $"(X,Y) = {e.X}, {e.Y}";
    label4.Text = mspos;
    Invalidate();
}
728x90