Can I draw a rectangle with mouseClick? My code is not working so far. Can you help me?
private void panel1_MouseClick(object sender, MouseEventArgs e)
{
Try this code with a PictureBox instead (just to get you started - there are many different ways of doing this):
private void pictureBox1_Click(object sender, EventArgs e)
{
if (pictureBox1.Image == null)
{
pictureBox1.Image = new Bitmap(pictureBox1.width,
pictureBox1.height);
}
using (Graphics g = Graphics.FromImage(pictureBox1.Image))
{
// draw black background
g.Clear(Color.Black);
Rectangle rect = new Rectangle(100, 100, 200, 200);
g.DrawRectangle(Pens.Red, rect);
}
pictureBox1.Invalidate();
}
This technique will automatically "persist" your drawing, meaning that it won't disappear if another windows gets dragged across it. When you draw to a control directly (what you're trying to do with the CreateGraphics() call) you usually run into the problem of non-persistency.
Update: here's another answer with a more detailed example of drawing something in response to where the mouse is clicked:
how to draw drawings in picture box