I am trying to create a rectangle which moves with the pointer in order to make it more clear for the user to see on which part of the screen the mouse pointer is. So far I managed to create the rectangle but I have a problem, each movement the pointer makes it is creating a new rectangle but I need to remove the old ones. this means that I only want ONE rectangle which moves around with the mouse pointer. This is my code so far. Could you please help?
PS I already user the clear() method and this.Invalidate();
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();
}
}
Instead of drawing to the form, I would create a custom cursor.
Instructions are available here:
https://msdn.microsoft.com/en-us/library/system.windows.forms.cursor%28v=vs.110%29.aspx
Set Form1 DoubleBuffer
property to true
.
Use Form1 paint
event to draw:
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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.