[C# 윈폼] C# 윈폼 마우스위치에 따라서 Panel 컬러(색상) 변경하기(MouseHover, MouseLeave)


안녕하세요.

 

오늘은 C# 윈폼에서 Panel 컨트롤에 대해서 알아보려고 합니다.

 

그 중에서도 Panel 컨트롤에 마우스를 가져다 대면 Background Color 가 변경이 되고, 다시 마우스가 Panel의 영역을 벗어나면 다시 원래 배경의 색으로 돌아 오게 끔 한번 예제 코드를 작성해 보려고 합니다.


 

그럼, 빈 윈폼 프로젝트를 생성해 주시고 Panel 컨트롤을 아래와 같이 배치해 주시기 바랍니다.

 

빈 윈폼 프로젝트 생성 및 Panel 컨트롤 배치



위와 같이 빈 윈폼에서 Panel 컨트롤 하나를 배치하였습니다.

 

Panel 컨트롤의 Name“uiPanel_Main” 이라고 지정하도록 하겠습니다.


그럼 이제, 마우스를 Panel 영역에 들어가면 컬러가 바뀌고, 다시 영역을 벗어나면 원래 배경 색으로 돌아오도록 하는 예제 코드를 작성해 보도록 하겠습니다.

 

예제 코드


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

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 PanelControlTest

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

 

            //이벤트 선언

            InitEvent();

        }

 

        /// <summary>

        /// 각종 컨트롤 이벤트 선언

        /// </summary>

        private void InitEvent()

        {

            this.uiPanel_Main.MouseHover += UiPanel_MouseHover_Event;

            this.uiPanel_Main.MouseLeave += UiPanel_MouseLeave_Event;

        }

 

        /// <summary>

        /// 마우스 Hover 이벤트 핸들러

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        public void UiPanel_MouseHover_Event(object sender, EventArgs e)

        {

            //마우스가 영역안에 들어오면 컬러 변경

            Panel pnl = sender as Panel;

 

            pnl.BackColor = Color.Red;

        }

 

        /// <summary>

        /// 마우스 Leave 이벤트 핸들러

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        public void UiPanel_MouseLeave_Event(object sender, EventArgs e)

        {

            //마우스가 영역 안을 벗어나게 되면

            Panel pnl = sender as Panel;

 

            pnl.BackColor = Color.Yellow;

        }

    }

}

 

Colored by Color Scripter

cs

 

실행 결과



위와 같이 기본적으로 프로그램을 실행 시키면 Panel 컨트롤의 기본색은 Yellow 로 지정이 되어 있고, 이제 마우스를 Panel 컨트롤 영역에 가져다 대면 Red 색상으로 변경되는 것을 확인하실 수 있습니다.

 

그리고 다시 마우스가 Panel 영역에 벗어나게 되면 Yellow 색상으로 변경되는 것을 확인하실 수 있습니다.

 

감사합니다.^^


728x90

이 글을 공유하기

댓글

Designed by JB FACTORY