본문 바로가기
코스웨어/15년 스마트컨트롤러

2015-06-11 32번 천정호

by 알 수 없는 사용자 2015. 6. 13.
728x90
반응형

----- C# -----

Window Form을 이용한 프로그램


Window Form Project를 생성한다.


Window Form Project 생성 화면


ToolBox





기본적으로 좌측에 보면 ToolBox라는탭이 존재한다.

이 탭은 Window Form에 사용될 버튼과 체크박스, 텍스트박스 등의 여러 메뉴들이 있는데

여기서 사용자가 원하는 메뉴를 가져와서 From에 넣어 사용할 수 있다.


Design Form

화면 중앙에 위치하는 Design Form 화면

ToolBox의 내용들을 Design Form에 추가하여 정렬한다.


Solution Explorer

현재 생성된 파일들 볼수있다.


Properties

ToolBox에서 가져온 항목들의 세부 정보와 수정이 가능한 곳으로 코드에서 수정보다는

Properties에서의 수정이 훨씬 쉽고 간편하게 이루어진다.


Console Application Project에서 Window Form을 사용하기 위하여 References 추가

Console Application Project에서는 Window Form을 사용 할수가없다.

그렇기 때문에 Solution Explorer에서 References 항목을 눌러 오른쪽 클릭을 하면

Add References를 통하여 WindowForms를 추가하여야 한다.


System.WindowsForms 추가하기

Add References를 실행하면 위와 같은 창이 뜨는데 우측 Framework를 누르면 현재 추가되어있는 Framework 종류와 추가 가능한 Framework의 종류가 나온다 여기서 System.Windows.Forms를 선택하여 좌측 체크박스를 클릭하여 추가하고 OK를 눌러 빠져나온다.

Console Application에서는 WindowsForm을 추가해야 하지만 Project 생성시에 Windows Form Application으로 생성한다면 자동으로 추가되어 생성되므로 따로 추가할 필요는 없다.


Project 생성 직후 Design Form 코드

Form1.Designer.cs

namespace CShap_2015_06_11_Window_Form_Program

{

    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()

        {

            this.components = new System.ComponentModel.Container();

            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;

            this.Text = "Form1";

        }


        #endregion

    }

}

#region과 #endregion으로 코드를 감싸게 되면 #region 옆의 문구로 코드가 블록화 되어 사용자에게 보여진다.


Form에 버튼 추가

ToolBox에서 Form에 버튼을 추가하면 버튼의 생성 순서에따라 번호가 붙어 생성된다.

Form에 생성된 버튼을 더블클릭하게 되면 버튼클릭 이벤트 메소드가 생성되며 생성된 코드의 위치로 이동한다.


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 CShap_2015_06_11_Window_Form_Program

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }


        private void button1_Click(object sender, EventArgs e)

        {


        }


        private void button2_Click(object sender, EventArgs e)

        {


        }

    }

}

private void button1_Click(object sender, EventArgs e)
private void button2_Click(object sender, EventArgs e)
이렇게 버튼1, 버튼2에 해당하는 클릭 이벤트 메소드가 생겼다.

각 각의 메소드에 사용자가 버튼을 클릭할때 어떤 이벤트를 실행할것인지를 작성하면 된다.

throw new NotImplementedException();    =>    버튼이 클릭되면 예외처리 출력
MessageBox.Show(sender.ToString());      =>    버튼이 클릭되면 메세지 박스를 통하여 버튼의 문자열 출력
MessageBox.Show(e.ToString());            =>    버튼이 클릭되면 메세지 박스를 통하여 이벤트 메세지 출력
Application.Exit();                                    =>    프로그램의 종료



Form1.Designer.cs

namespace CShap_2015_06_11_Window_Form_Program

{

    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()

        {

            this.button1 = new System.Windows.Forms.Button();

            this.button2 = new System.Windows.Forms.Button();

            this.SuspendLayout();

            // 

            // button1

            // 

            this.button1.Font = new System.Drawing.Font("Gulim", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(129)));

            this.button1.Location = new System.Drawing.Point(12, 12);

            this.button1.Name = "button1";

            this.button1.Size = new System.Drawing.Size(75, 23);

            this.button1.TabIndex = 0;

            this.button1.Text = "button1";

            this.button1.UseVisualStyleBackColor = true;

            this.button1.Click += new System.EventHandler(this.button1_Click);

            // 

            // button2

            // 

            this.button2.Font = new System.Drawing.Font("Gulim", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(129)));

            this.button2.Location = new System.Drawing.Point(197, 12);

            this.button2.Name = "button2";

            this.button2.Size = new System.Drawing.Size(75, 23);

            this.button2.TabIndex = 1;

            this.button2.Text = "button2";

            this.button2.UseVisualStyleBackColor = true;

            this.button2.Click += new System.EventHandler(this.button2_Click);

            // 

            // Form1

            // 

            this.AutoScaleDimensions = new System.Drawing.SizeF(13F, 24F);

            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;

            this.ClientSize = new System.Drawing.Size(284, 261);

            this.Controls.Add(this.button2);

            this.Controls.Add(this.button1);

            this.Name = "Form1";

            this.Text = "Form1";

            this.ResumeLayout(false);


        }


        #endregion


        private System.Windows.Forms.Button button1;

        private System.Windows.Forms.Button button2;

    }

}

각 ToolBox에서 추가한 메뉴들의 속성이 저장되어있다.

Console 환경에서는 각각의 메뉴의 속성을 사용자가 직접 구현해야하지만 Windows Form에서는 마우스로 추가와 Properties 속성에서 쉽고 간편하게 접근하여 수정할 수 있다.

그리고 Windows Form이 아닌 일반 Console 프로그램에서는 Form의 디자인과 각 메뉴의 이벤트 처리를 모두 한곳에서 처리하지만 Windows Form에서는 partial이라는 명령을 이용하여 디자인부와 메뉴의 이벤트 발생부분을 분리하여 작성할수가 있으므로 코드의 가독성이 높아지고 기능과 디자인의 분리구현으로 인하여 좀 더 편리하게 개발을 할수가 있게 되었다.


위의 수업내용을 통하여 구현한 책의 예제

예제의 Design Form 모습


Program.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using System.Windows.Forms;


namespace CShap_2015_06_11_WindowForm_Example

{

    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());

        }

    }

}


Form1.Design.cs

namespace CShap_2015_06_11_WindowForm_Example

{

    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()

        {

            this.grpFont = new System.Windows.Forms.GroupBox();

            this.textSampleText = new System.Windows.Forms.TextBox();

            this.chkItalic = new System.Windows.Forms.CheckBox();

            this.chkBold = new System.Windows.Forms.CheckBox();

            this.cboFont = new System.Windows.Forms.ComboBox();

            this.lblFont = new System.Windows.Forms.Label();

            this.grpFont.SuspendLayout();

            this.SuspendLayout();

            // 

            // grpFont

            // 

            this.grpFont.Controls.Add(this.textSampleText);

            this.grpFont.Controls.Add(this.chkItalic);

            this.grpFont.Controls.Add(this.chkBold);

            this.grpFont.Controls.Add(this.cboFont);

            this.grpFont.Controls.Add(this.lblFont);

            this.grpFont.Font = new System.Drawing.Font("Gulim", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(129)));

            this.grpFont.Location = new System.Drawing.Point(12, 12);

            this.grpFont.Name = "grpFont";

            this.grpFont.Size = new System.Drawing.Size(293, 81);

            this.grpFont.TabIndex = 0;

            this.grpFont.TabStop = false;

            this.grpFont.Text = "ComboBox, CheckBox, TextBox";

            this.grpFont.Enter += new System.EventHandler(this.groupBox1_Enter);

            // 

            // textSampleText

            // 

            this.textSampleText.Location = new System.Drawing.Point(8, 48);

            this.textSampleText.Name = "textSampleText";

            this.textSampleText.Size = new System.Drawing.Size(270, 20);

            this.textSampleText.TabIndex = 4;

            this.textSampleText.Text = "Hello, C#";

            // 

            // chkItalic

            // 

            this.chkItalic.AutoSize = true;

            this.chkItalic.Font = new System.Drawing.Font("Gulim", 8.25F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(129)));

            this.chkItalic.Location = new System.Drawing.Point(221, 25);

            this.chkItalic.Name = "chkItalic";

            this.chkItalic.Size = new System.Drawing.Size(57, 15);

            this.chkItalic.TabIndex = 3;

            this.chkItalic.Text = "이탤릭";

            this.chkItalic.UseVisualStyleBackColor = true;

            this.chkItalic.CheckedChanged += new System.EventHandler(this.chkItalic_CheckedChanged);

            // 

            // chkBold

            // 

            this.chkBold.AutoSize = true;

            this.chkBold.Font = new System.Drawing.Font("Gulim", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(129)));

            this.chkBold.Location = new System.Drawing.Point(169, 25);

            this.chkBold.Name = "chkBold";

            this.chkBold.Size = new System.Drawing.Size(48, 15);

            this.chkBold.TabIndex = 2;

            this.chkBold.Text = "굵게";

            this.chkBold.UseVisualStyleBackColor = true;

            this.chkBold.CheckedChanged += new System.EventHandler(this.chkBold_CheckedChanged);

            // 

            // cboFont

            // 

            this.cboFont.FormattingEnabled = true;

            this.cboFont.Items.AddRange(new object[] {

            "굵게",

            "이탤릭",

            "신명조"});

            this.cboFont.Location = new System.Drawing.Point(42, 23);

            this.cboFont.Name = "cboFont";

            this.cboFont.Size = new System.Drawing.Size(121, 19);

            this.cboFont.TabIndex = 1;

            this.cboFont.SelectedIndexChanged += new System.EventHandler(this.cboFont_SelectedIndexChanged);

            // 

            // lblFont

            // 

            this.lblFont.AutoSize = true;

            this.lblFont.Location = new System.Drawing.Point(6, 26);

            this.lblFont.Name = "lblFont";

            this.lblFont.Size = new System.Drawing.Size(30, 11);

            this.lblFont.TabIndex = 0;

            this.lblFont.Text = "Font";

            // 

            // Form1

            // 

            this.AutoScaleDimensions = new System.Drawing.SizeF(13F, 24F);

            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;

            this.ClientSize = new System.Drawing.Size(319, 209);

            this.Controls.Add(this.grpFont);

            this.Name = "Form1";

            this.Text = "Control Test";

            this.Load += new System.EventHandler(this.Form1_Load);

            this.grpFont.ResumeLayout(false);

            this.grpFont.PerformLayout();

            this.ResumeLayout(false);


        }


        #endregion


        private System.Windows.Forms.GroupBox grpFont;

        private System.Windows.Forms.CheckBox chkItalic;

        private System.Windows.Forms.CheckBox chkBold;

        private System.Windows.Forms.ComboBox cboFont;

        private System.Windows.Forms.Label lblFont;

        private System.Windows.Forms.TextBox textSampleText;

    }

}


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 CShap_2015_06_11_WindowForm_Example

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }


        void ChangeFont()

        {

            if (cboFont.SelectedIndex < 0)

                return;


            FontStyle style = FontStyle.Regular;


            if (chkBold.Checked)

                style |= FontStyle.Bold;


            if (chkItalic.Checked)

                style |= FontStyle.Italic;


            textSampleText.Font = new Font((string)cboFont.SelectedItem, 10, style);

        }


        private void groupBox1_Enter(object sender, EventArgs e)

        {

            

        }


        private void chkBold_CheckedChanged(object sender, EventArgs e)

        {

            ChangeFont();

        }


        private void Form1_Load(object sender, EventArgs e)

        {

            var Fonts = FontFamily.Families;

            foreach (FontFamily font in Fonts)

                cboFont.Items.Add(font.Name);

        }


        private void chkItalic_CheckedChanged(object sender, EventArgs e)

        {

            ChangeFont();

        }


        private void cboFont_SelectedIndexChanged(object sender, EventArgs e)

        {

            ChangeFont();

        }

    }

}




----- C++ -----

생성자, 복사생성자, 임시객체, 소멸자의 응용

//

//  main.cpp

//  C++ 2015-06-11 Car Class

//

//  Created by Cheon JeongHo on 2015. 6. 11..

//  Copyright (c) 2015년 Cheon JeongHo. All rights reserved.

//


#include <iostream>


using namespace std;


class Car {

private:

    int iColor;

    int iSpeed;

    char * cName;

    

    void CarName(const char *);


public:

    Car();

    Car(const char *);

    Car(const Car &);

    ~Car();

    

    void SetColor(int);

    void SetSpeed(int);

    void SetName(const char *);

    void Print(ostream * IN);

    const Car operator=(const Car &);

    void operator+=(Car & IN);

};


// 생성자

Car::Car() {

    CarName("Car");

}


// 인자가 하나인 생성자

Car::Car(const char * T) {

    CarName(T);

}


// 복사 생성자

Car::Car(const Car & T) {

    iColor = T.iColor;

    iSpeed = T.iSpeed;

    

    cName = new char[strlen(T.cName) + 1];

    

    strcpy(cName, T.cName);

    

    cout << cName << " 복사 생성자\n";

}


// 중복코드 사용을 막기위해 함수로 분리

void Car::CarName(const char * T) {

    iColor = 0;

    iSpeed = 0;

    

    cName = new char[strlen(T) + 1];

    

    strcpy(cName, T);

    

// 전처리 언어는 항상 가장 앞으로 옮겨져서 사용

// cl, gcc로 컴파일시에는 -DDEDUG 명령을 추가로 주면 실행

#ifdef DEDUG

    cout << cName << " 생성자\n";

#endif /* DEDUG */

}


// 소멸자

Car::~Car() {

// cl, gcc로 컴파일시에는 -DDEDUG 명령을 추가로 주면 실행

#ifdef DEDUG

    cout << cName << " 소멸자\n";

#endif /* DEDUG */

    

    delete []cName;

}


void Car::SetColor(int color) {

    iColor = color;

    

    cout << cName << " : " << Car::iColor << "로 iColor 값 변경\n";

}


void Car::SetSpeed(int speed) {

    iSpeed = speed;

    

    cout << cName << " : " << Car::iSpeed << "로 iSpeed 값 변경\n";

}


void Car::SetName(const char * T) {

    // 새로운 동적할당을 받기위하여 기존의 동적할당 해제

    delete []cName;

    // 새로운 동적할당 (입력받은 크기만큼 동적할당)

    cName = new char[strlen(T) + 1];

    

    strcpy(cName, T);

    

    cout << cName << " : " << T << "로 iSpeed 값 변경\n";

}


const Car Car::operator=(const Car & T) {

    SetColor(T.iColor);

    SetSpeed(T.iSpeed);

    SetName(T.cName);

    

    cout << "-------------------------\n";

    cout << "\nReturn 후 임시객체 생성\n\n";

    

    // *this를 리턴하면 복사생성자가 호출되어서 소멸자가 한번 더 생성

    return *this;

}


int main() {

//    Car obj1;

//    

//    obj1.SetColor(100);

//    obj1.SetSpeed(200);

//    obj1.SetName("ABCDEFG");

//    

//    Car obj2(obj1);


    // Car Class만 생성되고 소멸

    Car car1;

    Car car2("Benz");

    Car car3("BMW");

    

// 복사 생성자 실행

// car2 = car1;

    // operator 함수의 반환형이 void이면 car1 = car3의 결과값은 void

    // 그 이유는 함수의 반환형이 void형이기 때문에 car2에는 void가 들어가므로 에러가 발생

    // 해결책은 operator 함수의 반환형을 대입할 곳과 같은 Car class형 같게 변경

    // 그 후 연산된 결과는 변하면 안되기 때문에 const로 변경

    // car3 = car1의 반환값은 class 자체에 존재하기 때문에 *this로 객체를 리턴하여 대입

    car2 = car3 = car1;

    

    return 0;

}


728x90