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

时间:2016-07-12 02:30:03

标签: c# windows-forms-designer hittest drawrectangle

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

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

2 个答案:

答案 0 :(得分:3)

如果你的" 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";
      }
    }
  }

答案 1 :(得分:1)

Rectangle有几个方便但经常被忽视的功能。在这种情况下,使用Rectangle.Contains(Point)函数是最佳解决方案:

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

要确定您是否点击大纲,您需要决定宽度,因为用户无法轻松点击单个像素。

为此,您可以使用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 

}

..或坚持矩形..:

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
}