Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want a drawn circle to follow my mouse in C#

Tags:

c#

winforms

First off, I'm a real beginer at C# so please be gentle.

I'm trying to have a circle follow my cursor. I don't want any "trails" to be left behind.

private void Form1_MouseMove(object sender, MouseEventArgs e)
{

    drawCircle(e.X, e.Y);

}

private void drawCircle(int x, int y)
{
    Pen skyBluePen = new Pen(Brushes.DeepSkyBlue);
    Graphics graphics = CreateGraphics();
    graphics.DrawEllipse(
        skyBluePen, x - 150, y - 150, 300, 300);
    graphics.Dispose();
    this.Invalidate();
}

This works ok, as it draws it and centers on the mouse for every mouse move. However, the "this.Invalidate();" is wrong. It "undraws" the shape after every movement, so I can only see glimpses of it. However, not including it causes every single drawn circle to remain on screen.

How do I get one circle to "gracefully" follow my mouse around, without being too jumpy and without retaining all of the past circles?

like image 728
ck_ Avatar asked Dec 01 '22 12:12

ck_


1 Answers

You can do something like this:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        Point local = this.PointToClient(Cursor.Position);
        e.Graphics.DrawEllipse(Pens.Red, local.X-25, local.Y-25, 20, 20);
    }

    private void Form1_MouseMove(object sender, MouseEventArgs e)
    {
        Invalidate();
    }
}

Basically, on the mouse move, invalidate. On the Paint, draw your circle.

like image 148
Erich Mirabal Avatar answered Dec 05 '22 00:12

Erich Mirabal