본문 바로가기

프로그래밍

[C#] 사각형 안으로 마우스 옮기면 테두리 색 변하게 하는 간단한 코드

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace WindowsApplication2
{
    public partial class Form1 : Form
    {
        private Rectangle rect;
        private bool inRect = false;
        private int a = 20, b = 70;
        public Form1()
        {
            InitializeComponent();
            rect = new Rectangle(70, 70, 70 + a, 70 + b);
        }
        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            g.DrawRectangle(Pens.Black, rect);
        }
        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            Graphics g = this.CreateGraphics();
            if(! inRect)
            {
                if(rect.Contains(e.X, e.Y))
                {
                    g.DrawRectangle(Pens.Pink, rect);
                    inRect = true;
                    return;
                }
            } else if( inRect )
            {
                if(!rect.Contains(e.X, e.Y))
                {
                    Invalidate();
                    inRect = false;
                    return;
                }
            }
        }
    }
}