繁体   English   中英

C#Drawing Rectangle鼠标事件

[英]C# Drawing Rectangle On the mouse event

我想画一个矩形。 我想要的是向用户显示鼠标事件上的矩形。 在此输入图像描述

就像在图像中。 这适用于C#.net Forms应用程序。

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

谢谢Yohan

您可以分三步完成:

  • 首先检查是否按下了鼠标
  • 如果是鼠标移动事件,则在拖动鼠标时继续使用新位置初始化矩形
  • 然后在paint事件上绘制矩形。 (几乎每个鼠标事件都会引发,取决于鼠标刷新率和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);
        }

    }
}

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM