在指针位置创建矩形

时间:2015-02-17 15:35:45

标签: c# winforms graphics mouseevent

我正在尝试创建一个随指针移动的矩形,以便让用户更清楚地看到鼠标指针在屏幕的哪个部分。到目前为止,我设法创建矩形,但我有一个问题,指针使每个移动创建一个新的矩形,但我需要删除旧的矩形。这意味着我只想要一个用鼠标指针移动的矩形。到目前为止这是我的代码。能否请你帮忙?

P.S。我已经使用了clear()方法和this.Invalidate();

enter image description here

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    int posX = e.X;
    int posY = e.Y;

    Graphics g = Graphics.FromHwnd(IntPtr.Zero);

    mouseNewRect = new Rectangle(new Point(posX, posY), new Size(100, 100));

    if (mouseOldRect.X != mouseNewRect.X || mouseOldRect.Y != mouseNewRect.Y)
    {
         mouseOldRect = mouseNewRect;

         g.DrawRectangle(new Pen(Brushes.Chocolate), mouseNewRect);
        // this.Invalidate();
     }
}

2 个答案:

答案 0 :(得分:2)

我会创建一个自定义光标,而不是绘制到表单。

这里有说明:

https://msdn.microsoft.com/en-us/library/system.windows.forms.cursor%28v=vs.110%29.aspx

答案 1 :(得分:0)

将Form1 DoubleBuffer属性设置为true

使用Form1 paint事件绘制:

bool drawRect = false;

private void Form1_Paint(object sender, PaintEventArgs e)
{
    if(drawRect)
    {
        e.Graphics.DrawRectangle(new Pen(Brushes.Chocolate), mouseNewRect);
    }
}

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    if(drawRect == false)
    {
        drawRect = true;
    }

    mouseNewRect = new Rectangle(new Point(e.X, e.Y), new Size(100, 100));

    this.Invalidate();
}

private void Form1_MouseLeave(object sender, EventArgs e)
{
    //This will erase the rectangle when the mouse leaves Form1
    drawRect = false;

    this.Invalidate();
}