프로그래밍/C#
Form 상속
에어버스
2020. 12. 17. 23:39
Paint 이벤트처리기 : https://petra.tistory.com/1549
1
2
3
4
5
6
7
8
9
10
11 |
class Class1 : System.Windows.Forms.Form
{
public static void Main()
{
Class1 form = new Class1();
form.Text = "Form 상속";
form.BackColor = System.Drawing.Color.White;
System.Windows.Forms.Application.Run(form); // 이 코드가 없으면 창이 나왔다가 바로 사라지면서 종료된다.
}
} |
cs |
실행결과>
1
2
3
4
5
6
7
8
9
10
11
12
13 |
class Class1 : System.Windows.Forms.Form
{
public static void Main()
{
System.Windows.Forms.Application.Run(new Class1()); // 이 코드가 없으면 창이 나왔다가 바로 사라지면서 종료된다.
}
public Class1() // 생성자 함수
{
Text = "Form 상속";
BackColor = System.Drawing.Color.White;
}
} |
cs |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 |
class Class1 : System.Windows.Forms.Form
{
public static void Main()
{
System.Windows.Forms.Application.Run(new Class1()); // 이 코드가 없으면 창이 나왔다가 바로 사라지면서 종료된다.
}
public Class1() // 생성자 함수
{
Text = "Form 상속";
BackColor = System.Drawing.Color.White;
}
protected override void OnPaint(System.Windows.Forms.PaintEventArgs pea)
{
System.Drawing.Graphics grfx = pea.Graphics;
grfx.DrawString("Helloc, Windows Forms!", Font, System.Drawing.Brushes.Black, 0, 0);
}
} |
cs |
실행결과>
Form 상속이 좋은점
Form 인스턴스를 만들면 Form 에 구현된 Paint 이벤트(prorected OnPaint())처리를 위해 이벤트 핸들러를 등록해줘야 한다. (https://petra.tistory.com/1549)
그런데, Paint 이벤트핸들러 등록할 필요가 없이 OnPaint()를 재정의해서 바로 사용하면 된다.
Control을 상속받은 클래스에서는 Paint 이벤트 핸들러를 설치할 필요없이 protected 인 OnPaint()를 재정의하면 된다.
VS2019 에서 프로젝트를 윈도우 폼 형식으로 만들면 자동 생성된 코드는 다음과 같다. (위 코드와 유사함)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
static class Program
{
/// <summary>
/// 해당 애플리케이션의 주 진입점입니다.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// 버튼 클릭 이벤트 처리기가 만들어진 곳
private void button1_Click(object sender, EventArgs e)
{
}
protected override void OnPaint(System.Windows.Forms.PaintEventArgs pea)
{
System.Drawing.Graphics grfx = pea.Graphics;
grfx.DrawString("Helloc, Windows Forms!", Font, System.Drawing.Brushes.Black, 0, 0);
}
}
}
namespace WindowsFormsApp1
{
partial class Form1
{
...
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "Form1";
}
}
} |
cs |
실행화면>