C#在鼠标事件上绘制矩形

4

我想要绘制一个矩形。我希望在鼠标事件上显示给用户这个矩形,就像图片中所示。这是针对C# .net窗体应用程序的。请帮助我实现这个功能。感谢您的任何帮助。

谢谢
Yohan


这是一个橡皮筋选择矩形吗?还是您希望他们在表单上绘制一个永久的形状轮廓? - Cody Gray
是的,这是橡皮筋选择,不是永久性的。 - yohan.jayarathna
3个回答

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);
        }

    }
}

稍后如果您想检查按钮(如图所示)是否在矩形内,您可以通过检查按钮的区域并检查它们是否位于您绘制的矩形中来实现。


嗨,这个完美地运行了。我尝试在pictureBox控件事件上做同样的事情,但它没有起作用。我做错了什么吗? - yohan.jayarathna
它之前是可以工作的,但可能是在picturebox(在窗体上)下面绘制的..给我看看你尝试过的代码..还要检查@hans Passant的答案..他的技巧可以在任何地方使用。 - Shekhar_Pro
1
好的,现在它可以工作了,在我的情况下,应该是this.Invalidate(); 应改为 pictureBox1.Invalidate(); 非常感谢 :) - yohan.jayarathna

4

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);
}

3

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接