在面板上单击鼠标并在其中更改颜色时绘制一个矩形

时间:2014-03-08 17:44:42

标签: c# winforms

我想在点击鼠标的面板上绘制一个矩形。当用户再次单击相同的矩形时,它将更改其颜色。它必须在一个小组上绘制。

我在互联网的帮助下所做的就是这样。它会在首先绘制的矩形坐标之间显示一条消息鼠标。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public int xcord1;
    public int ycord1;

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

    private void panel1_MouseClick(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {              
            //Gets a color for the rectangle
            Color c = Color.Blue;

            //Adds the rectangle using the color as the key for the dictionary

            if (!rectangles.ContainsKey(c))
            {
                rectangles.Add(c, new List<Rectangle>());
            }
            if (textBox1.Text.Length == 0 && textBox2.Text.Length == 0)
            {
                textBox1.Text = e.Location.X.ToString();
                textBox2.Text = e.Location.Y.ToString();
                xcord1 = int.Parse(textBox1.Text);
                ycord1 = int.Parse(textBox2.Text);
            }
            if (Cursor.Position.X <= xcord1 + 100 && Cursor.Position.X >= xcord1 
                && Cursor.Position.Y <= ycord1 + 100 && Cursor.Position.Y >= ycord1)
            {    
                MessageBox.Show("click");                   
            }
            else
            {
                rectangles[c].Add(new Rectangle(e.Location.X - 12, e.Location.Y - 12,100,100));
                //Adds the rectangle to the collection
            }
        }       
        //Make the panel repaint itself.
        panel1.Refresh();          
    }

    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)
        {
            //Create the pen used to draw the rectangle (using statement makes sure the pen is disposed)
            using (var pen = new Pen(rectKey))     
            {
                //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());
            }
        }
    }
}









}

0 个答案:

没有答案