[윈폼 컨트롤] 윈폼 컬러(Color) 콤보박스(ComboBox) 만드는 방법


안녕하세요.

 

오늘은 윈폼 기본 컨트롤 중 하나인 콤보박스를 응용하여 컬러 콤보박스 만드는 방법에 대해서 알려드리고자 해요.

 

오늘 사용하는 소스코드는 제가 직접 구현한 것이 아니라, 오픈소스를 이용하여 구현한 것입니다.

 

그럼 바로 알려드리도록 하겠습니다.



1. 윈폼 프로젝트 생성


제일 먼저 비쥬얼 스튜디오에서 윈폼 프로젝트를 생성해 주시기 바랍니다.



이렇게 빈 윈폼 프로젝트를 생성 하셨다면 이제 사용자 정의 컨트롤(유저컨트롤) 을 생성해주시기 바랍니다.


2. 사용자 정의 컨트롤 생성



저는 위와같이 사용자 정의 컨트롤 이름을 ColorComboBox.cs 라고 생성하였습니다.


3. ColorComboBox.cs 코드 작성


2번에서 생성한 사용자 정의 컨트롤을 아래와 같이 코드를 작성해 주시기 바랍니다.


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

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Drawing;

using System.Data;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

 

namespace CustomColoredCombobox

{

    public partial class ColorComboBox : ComboBox

    {

          //the default colors from list

        private string[] arr_MyColors = { "Black""Red""Blue""Green" };  

        protected int inMargin;

        protected int boxWidth;

        private Color c;

         

         //public proprties to interact with control from proprties window

        public string[] MyColors  

        {

            get { return arr_MyColors; }

            set

            {

                int col_numbers = value.Length;

                arr_MyColors = new string[col_numbers];

                for (int i = 0; i < col_numbers; i++)

                    arr_MyColors[i] = value[i];

                this.Items.Clear();

                InitCombo();

            }

        }

        public ColorComboBox()  //constructor

        {

            DrawMode = DrawMode.OwnerDrawFixed;

            DropDownStyle = ComboBoxStyle.DropDownList;

            inMargin = 2;

            boxWidth = 3;

            BeginUpdate();

            InitCombo();

            EndUpdate();

        }

 

        private void InitCombo() //add items 

        {

            if (arr_MyColors == nullreturn;

            foreach (string color in arr_MyColors)

            {

                try

                {

                    if (Color.FromName(color).IsKnownColor)

                        this.Items.Add(color);

                }

                catch

                {

                    throw new Exception("Invalid Color Name: " + color);

                }

            }

        }

 

        protected override void OnDrawItem(DrawItemEventArgs e)

        {

            base.OnDrawItem(e);

            if ((e.State & DrawItemState.ComboBoxEdit) != DrawItemState.ComboBoxEdit)

                e.DrawBackground();

 

            Graphics g = e.Graphics;

            if (e.Index == -1)  //if index is -1 do nothing

                return;

            c = Color.FromName((string)base.Items[e.Index]);

 

            //the color rectangle

            g.FillRectangle(new SolidBrush(c), e.Bounds.X + this.inMargin, e.Bounds.Y + 

this.inMargin, e.Bounds.Width / this.boxWidth - 2 * this.inMargin,

 e.Bounds.Height - 2 * this.inMargin);

            //draw border around color rectangle

            g.DrawRectangle(Pens.Black, e.Bounds.X + this.inMargin, e.Bounds.Y +

 this.inMargin, e.Bounds.Width / this.boxWidth - 2 * this.inMargin,

 e.Bounds.Height - 2 * this.inMargin);

            //draw strings

            g.DrawString(c.Name, e.Font, new SolidBrush(ForeColor), (float)(e.Bounds.Width / this.boxWidth + 5 * this.inMargin), (float)e.Bounds.Y);

        }

    }

}

 

 

Colored by Color Scripter

cs

 

이렇게 코드를 작성하셨다면, ColorComboBox.Designer.cs에서 빨간줄이 그어지면서 오류 표시가 생기게 됩니다.


빨간줄이 생긴 ColorComboBox.Designer.cs를 삭제 해 주시면 됩니다.

 

4. 빌드 -> 솔루션 빌드




3번과정까지 다 하셨다면, 이제 ColorComboBox 사용자 정의 컨트롤을 다 만든 것입니다. 비쥬얼 스튜디오 상단에 빌드 메뉴에서 솔루션 빌드를 다시 해주시기 바랍니다.

 

솔루션 빌드를 하고 나면 도구상자에 아래와 같이 ColorComboBox 컨트롤이 생기신 것을 확인하실 수 있습니다.



 

5. 도구상자에서 ColorComboBox 배치





앞에서 만들었던 ColorComboBox 컨트롤을 윈폼 메인에 배치해 주시기 바랍니다.

 

여기까지 하셨다면 속성창에 가셔서 MyColors 속성에 기본으로 설정해 주었던 “Black”, “Red”, “Blue”, “Green” 컬러 말고 “Yellow”, “Orange”, “DarkOrange”, “Pink”, “Aqua”를 추가해 보겠습니다.






위와 같이 MyColors 속성에 컬러들이 추가된 것을 보실 수 있습니다.


 

참고로 컬러 추가는 String[] Array 있는 부분에 마우스 클릭 하셔서 직접 입력하셔야 합니다!

 

실행 결과



 

1번부터 6번까지 모두 다 따라하셨다면, 이제 메인 폼을 실행 시켜 주시면 위와 같이 콤보박스에 컬러들이 같이 들어가서 보이는 것을 확인하실 수 있습니다!^^

 

해당 컨트롤을 가지고 여러가지로 응용이 가능하기 때문에, 필요하신 분들은 한번씩 따라하시면서 필요한 곳에 사용하시면 될거에요!ㅎㅎ

 

감사합니다^^


728x90

이 글을 공유하기

댓글

Designed by JB FACTORY