我做了一个矩形如何检查鼠标是否点击了它?

Kil*_*yfe 2 c# drawrectangle windows-forms-designer hittest

如何检查鼠标是否单击了矩形?

Graphics gfx;
Rectangle hitbox;
hitbox = new hitbox(50,50,10,10);
//TIMER AT THE BOTTOM
gfx.Draw(System.Drawing.Pens.Black,hitbox);
Run Code Online (Sandbox Code Playgroud)

小智 5

只是一个快速而肮脏的示例,如果您的“gfx”是来自表单的“e.Graphics...”:

  public partial class Form1 : Form
  {
    private readonly Rectangle hitbox = new Rectangle(50, 50, 10, 10);
    private readonly Pen pen = new Pen(Brushes.Black);

    public Form1()
    {
      InitializeComponent();
    }

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
      e.Graphics.DrawRectangle(pen, hitbox);
    }

    private void Form1_MouseDown(object sender, MouseEventArgs e)
    {
      if ((e.X > hitbox.X) && (e.X < hitbox.X + hitbox.Width) &&
          (e.Y > hitbox.Y) && (e.Y < hitbox.Y + hitbox.Height))
      {
        Text = "HIT";
      }
      else
      {
        Text = "NO";
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)