[C# 윈폼] Panel 영역에 마우스 올렸을 때, Cursor 변경하기


안녕하세요.

 

오늘은 마우스를 특정 Panel 영역에 올렸을 때, 마우스 Cursor(커서) 아이콘 변경하는 방법에 대해서 알려 드리도록 하겠습니다.

 

이 소스코드는 제가 작성한 것이 아닌, 저도 구글링을 하면서 찾은 소스코드를 가지고 조금 변경하여 정리한다는점 참고해 주시면 좋겠습니다!^^

 

그럼 바로 어떻게 소스코드로 구현을 하는지 보여 드리도록 하겠습니다.


 

먼저 빈 윈폼 프로젝트를 생성해 주시기 바랍니다.

 

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



빈 윈폼 프로젝트를 생성하였다면, 위와 같이 Panel 컨트롤을 하나 배치해 주시기 바랍니다.

 

Panel 컨트롤의 Name“panel1” 입니다.

 

그럼 바로 해당 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

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 PanelAreaTest

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

 

            InitEvent();

        }

 

        public void InitEvent()

        {

            this.panel1.MouseMove += Panel_MouseMove;

        }

 

        private void Panel_MouseMove(object sender, MouseEventArgs e)

        {

            this.panel1.Cursor = PanelArea(this.panel1).Contains(e.Location) ?

                                                Cursors.No : Cursors.Default;

        }

 

        Rectangle PanelArea(Panel panel)

        {

            Size si = panel.Size;

            Size sp = panel.ClientSize;

            float ri = 1f * si.Width / si.Height;

            float rp = 1f * sp.Width / sp.Height;

            if (rp > ri)

            {

                int width = si.Width * sp.Height / si.Height;

                int left = (sp.Width - width) / 2;

                return new Rectangle(left, 0, width, sp.Height);

            }

            else

            {

                int height = si.Height * sp.Width / si.Width;

                int top = (sp.Height - height) / 2;

                return new Rectangle(0, top, sp.Width, height);

            }

        }

    }

}

 

Colored by Color Scripter

cs

 

이렇게 작성하시고 이제 테스트를 해보시면 Panel 영역에 마우스를 가져다 대면, 마우스 커서가 “No” 아이콘으로 변경이 되고, 다시 Panel 영역을 벗어나면 일반 “Defalut” 아이콘으로 변경이 되는 것을 확인하실 수 있습니다.

 

감사합니다.^^


728x90

이 글을 공유하기

댓글

Designed by JB FACTORY