简体   繁体   中英

Draw rectangle where mouse clicked

I'm very new in C# I want a rectangle to appear wherever there's a mouseclick on a panel

Here's my code:

private void panel1_MouseClick(object sender, MouseEventArgs e)
{
  int x = e.Location.X;
  int y = e.Location.Y;

       if (radioButton1.Checked == false)
       {

                ((Panel)sender).Invalidate(new Rectangle(x * 40, y * 40, 40, 40));
       }
       else if (radioButton2.Checked == true)
       {
                return;
       }
}

I wonder how to change the color of the rectangle? Please advise me if my code is wrong. Thanks.

Your drawing should be performed in the panel's Paint event handler. When you click the panel, create the rectangle (in the MouseUp event of the panel) and store it in a collection of rectangles (such as a dictionary). Then refresh the panel. In the panel's Paint event, draw all the rectangles. Here is a simple example:

Dictionary<Color, List<Rectangle>> rectangles = new Dictionary<Color, List<Rectangle>>();

private void panel1_Paint(object sender, PaintEventArgs e)
{
    //The key value for the dictionary is the color to use to paint with, so loop through all the keys (colors)
    foreach (var rectKey in rectangles.Keys)
    {
        using (var pen = new Pen(rectKey))     //Create the pen used to draw the rectangle (using statement makes sure the pen is disposed)
        {
            //Draws all rectangles for the current color
            //Note that we're using the Graphics object that is passed into the event handler.
            e.Graphics.DrawRectangles(pen, rectangles[rectKey].ToArray());                    
        }
    }
}

//This method just adds the rectangle to the collection.
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
    if (e.Button == System.Windows.Forms.MouseButtons.Left)
    {
        Color c = getSelectedColor();     //Gets a color for which to draw the rectangle

        //Adds the rectangle using the color as the key for the dictionary
        if (!rectangles.ContainsKey(c))   
        {
            rectangles.Add(c, new List<Rectangle>());
        }
        rectangles[c].Add(new Rectangle(e.Location.X - 12, e.Location.Y - 12, 25, 25));    //Adds the rectangle to the collection
    }

    //Make the panel repaint itself.
    panel1.Refresh();
}
private void panel1_MouseClick(object sender, MouseEventArgs e)
{
    Graphics g = panel1.CreateGraphics();
    g.DrawRectangle(new Pen(Brushes.Black),  
    new Rectangle(new Point(e.X, e.Y), new  
        Size(100, 100)));
}

you can change the color in Brushes.Black part of code, change it as you desire

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM