Draw a rectangle on mouse click

前端 未结 4 674
终归单人心
终归单人心 2020-12-03 09:05

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)
{
            


        
4条回答
  •  天命终不由人
    2020-12-03 09:16

    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

提交回复
热议问题