抓不住的按钮:点与矩形运算、窗体重绘

using System;
using System.Drawing;
using System.Windows.Forms;

namespace e23
{
    public partial class Form1 : Form
    {
        private Rectangle btnRect;//警戒区
        private const int padding = 50;//警戒区感应范围
        public Form1()
        {
            InitializeComponent();
            getRect();
        }
        //生成警戒区,将按钮包围
        private void getRect()
        {
            Point p = button1.Location; p.Offset(-padding, -padding);
            btnRect = new Rectangle(p, new Size(button1.Width + padding*2, button1.Height + padding*2));
        }
        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            if (btnRect.Contains(e.Location))//如果鼠标进入警戒区
            {
                //生成一个随机点作为按钮位置,保证按钮显示完整
                Random r = new Random();
                Point p = new Point(
                    r.Next(button1.Width, this.Width - 2 * button1.Width),
                    r.Next(button1.Height, this.Height - 2 * button1.Height)
                    );
                button1.Location = p;
                //重新绘制警戒区
                this.Invalidate(btnRect);//消除旧的
                getRect();
                this.Invalidate(btnRect);//绘制新的
            }
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.FillRectangle(Brushes.Red, btnRect);//绘制警戒区
        }

        private void button1_MouseUp(object sender, MouseEventArgs e)
        {
            //使用MouseUp事件,不响应键盘操作
            //因为Form1_MouseMove响应的间隔性,按钮是有可能被点中的
            MessageBox.Show("WINNER WINNER CHICKEN DINNER");
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值