2

How do I check if a mouse clicked a rectangle?

Graphics gfx;
Rectangle hitbox;
hitbox = new hitbox(50,50,10,10);
//TIMER AT THE BOTTOM
gfx.Draw(System.Drawing.Pens.Black,hitbox);
TaW
  • 53,122
  • 8
  • 69
  • 111
Kill4lyfe
  • 21
  • 1
  • 2
  • What does your `gfx` refer to? – Tommy Jul 12 '16 at 02:34
  • If your "gfx" is a "e.Graphics..." from a form, then just use event MouseDown, there are e.X and e.Y. –  Jul 12 '16 at 02:36
  • Never use `control.CreateGraphics`! Never try to cache a `Graphics` object! Either draw into a `Bitmap bmp` using a `Graphics g = Graphics.FromImage(bmp)` or in the `Paint` event of a control, using the `e.Graphics` parameter.. – TaW Jul 12 '16 at 07:33

2 Answers2

5

Just a sample quick and dirty, if your "gfx" is a "e.Graphics..." from a Form:

  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";
      }
    }
  }
3

Rectangle has several handy but often overlooked functions. In this case using the Rectangle.Contains(Point) function is the best solution:

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
    if (hitbox.Contains(e.Location)) ..  // clicked inside
}

To determine if you clicked on the outline you will want to decide on a width, since the user can't easily hit a single pixel.

For this you can use either GraphicsPath.IsOutlineVisible(Point)..

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
    GraphicsPath gp = new GraphicsPath();
    gp.AddRectanle(hitbox);
    using (Pen pen = new Pen(Color.Black, 2f))
      if (gp.IsOutlineVisible(e.location), pen)  ..  // clicked on outline 

}

..or stick to rectangles..:

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
    Rectangle inner = hitbox;
    Rectangle outer = hitbox;
    inner.Inflate(-1, -1);  // a two pixel
    outer.Inflate(1, 1);    // ..outline

    if (outer.Contains(e.Location) && !innerContains(e.Location)) .. // clicked on outline
}
TaW
  • 53,122
  • 8
  • 69
  • 111