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");
}
}
}
抓不住的按钮:点与矩形运算、窗体重绘
最新推荐文章于 2024-07-02 08:00:00 发布