2011-03-01 60 views
4

我想绘制一个矩形。事情我想要的是显示用户矩形鼠标事件。 enter image description hereC#绘制矩形在鼠标事件上

像在图像中。这是针对C#.net Forms应用程序的。

帮我实现这个目标。任何帮助表示赞赏。

谢谢 勒芒

+0

这是一个橡皮筋选择矩形吗?或者你想让他们在表单上绘制永久形状轮廓? – 2011-03-01 06:34:52

+0

是的,它是橡皮筋的选择,而不是一个永久的 – 2011-03-01 06:44:30

回答

5

你能做到这一点的三个步骤:

  • 首先检查是否按下鼠标
  • 如果是则在鼠标移动事件保持初始化新矩形拖动鼠标时的位置
  • 然后在绘画事件上绘制矩形。 (它会被上调,几乎每一个鼠标事件,取决于鼠标的刷新率和DPI)

你可以做财产以后这样的(在你的Form):

public class Form1 
{ 

     Rectangle mRect; 

    public Form1() 
    { 
        InitializeComponents(); 

        //Improves prformance and reduces flickering 
     this.DoubleBuffered = true; 
    } 

      //Initiate rectangle with mouse down event 
    protected override void OnMouseDown(MouseEventArgs e) 
    { 
     mRect = new Rectangle(e.X, e.Y, 0, 0); 
     this.Invalidate(); 
    } 

      //check if mouse is down and being draged, then draw rectangle 
    protected override void OnMouseMove(MouseEventArgs e) 
    { 
     if(e.Button == MouseButtons.Left) 
     { 
      mRect = new Rectangle(mRect.Left, mRect.Top, e.X - mRect.Left, e.Y - mRect.Top); 
      this.Invalidate(); 
     } 
    } 

      //draw the rectangle on paint event 
    protected override void OnPaint(PaintEventArgs e) 
    { 
       //Draw a rectangle with 2pixel wide line 
     using(Pen pen = new Pen(Color.Red, 2)) 
     { 
     e.Graphics.DrawRectangle(pen, mRect); 
     } 

    } 
} 

后,如果您想检查按钮(如图所示)是矩形或不是,你可以通过检查Button的区域来检查它们是否位于你绘制的矩形中。

+0

嗨,这个作品完美,在pictureBox控件事件上试过同样的东西,但它没有奏效。我做错什么了吗? – 2011-03-01 08:35:11

+0

它正在工作,但可能它是在picturebox(在窗体上)下绘制的..向我展示你尝试的代码..也检查@hans Passant的答案..他的技巧将在每一个地方工作。 – 2011-03-01 08:39:11

+1

现在确定它的工作,在我的情况this.Invalidate();应该是pictureBox1.Invalidate();非常感谢你:) – 2011-03-01 08:42:09

2

那些蓝色矩形看起来很像控件。在Winforms中很难做到在控件上绘制一条线。您必须创建一个覆盖设计图面的透明窗口,并在该窗口上绘制矩形。这也是Winforms设计器的工作方式。示例代码is here

+0

+1好用的技巧..如果你还记得我自己的回答是来自你在MSDN上的回答之一,虽然它在这种情况下不起作用。 – 2011-03-01 06:50:57

3

通过Shekhar_Pro解决方案绘制一个矩形只是在一个方向(从上到下,从左到右),如果你想画一个矩形,无论鼠标位置和移动解决方案的方向:

Point selPoint; 
Rectangle mRect; 
void OnMouseDown(object sender, MouseEventArgs e) 
{ 
    selPoint = e.Location; 
    // add it to AutoScrollPosition if your control is scrollable 
} 
void OnMouseMove(object sender, MouseEventArgs e) 
{ 
    if (e.Button == MouseButtons.Left) 
    { 
     Point p = e.Location; 
     int x = Math.Min(selPoint.X, p.X) 
     int y = Math.Min(selPoint.Y, p.Y) 
     int w = Math.Abs(p.X - selPoint.X); 
     int h = Math.Abs(p.Y - selPoint.Y); 
     mRect = new Rectangle(x, y, w, h); 
     this.Invalidate(); 
    } 
} 
void OnPaint(object sender, PaintEventArgs e) 
{ 
    e.Graphics.DrawRectangle(Pens.Blue, mRect); 
}