This behavior in C# is bizarre. I have the following class to allow me to effectively ‘draw’ on the desktop:
class drawOnDesktop {
public static Form dodF = new Form();
public static Graphics formGraphics;
public drawOnDesktop() {
formGraphics = dodF.CreateGraphics();
dodF.BackColor = Color.LightGreen;
dodF.TransparencyKey = Color.LightGreen;
dodF.Size = new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
dodF.Location = new Point(0,0);
dodF.StartPosition = FormStartPosition.Manual;
//dodF.FormBorderStyle = FormBorderStyle.None;
dodF.WindowState = FormWindowState.Maximized;
dodF.MinimizeBox = false;
dodF.MaximizeBox = false;
dodF.ControlBox = false;
//dodF.TopMost = true; //For development in case something goes wrong
dodF.BringToFront();
dodF.Show();
}
public static void drawCircle(Point location) {
formGraphics.FillEllipse(Brushes.Black, location.X, location.Y, 10, 10);
}
}
And I call it like this, from my main form:
drawOnDesktop dod = new drawOnDesktop();
drawOnDesktop.drawCircle(new Point(100,100));
If you run that code, you’ll get a small black circle in the top left corner of your screen. The problem is that you can see the form’s border. Now, try commenting out the FormBorderStyle line. The black dot will appear for a fraction of a second, and disappear. Why!? As you can see, I’ve set a lot of properties on this form, and still it refuses to work. Is it getting repainted over by the OS?
I don’t need to worry about mouse events or things like that – the dots being placed on the screen are completely programmatic, and not from the user. As well, if I set dodF.ShowInTaskbar = false, the entire program crashes.
How can I fix this code so the dot appears and stays until I formGraphics.Clear(Color.Black)?
Don’t keep a copy of the graphics around, that is just asking for trouble. As others have stated, you should use the paint event to draw on the screen:
You can call it the same way, but now every time the form repaints, it will redraw the circles.