Событие Click для объекта Rectangle - C#
Формулировка задачи:
Есть такая простая программка:
Вопрос: как мне добавить событие, допустим клик мышкой, для прямоугольника
public partial class Form_Main : Form
{
private int WidthHeight = 30;
private Rectangle[,] _rectangles = new Rectangle[8, 8];
private Pen _blackPen = new Pen(Color.Black, 1);
public Form_Main()
{
InitializeComponent();
pictureBox1.Invalidate();
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
Graphics paper = e.Graphics;
Nets(paper);
}
private void Nets(Graphics paper)
{
Point a = new Point(pictureBox1.Left, pictureBox1.Top);
_rectangles[0, 0] = new Rectangle(a.X, a.Y, WidthHeight, WidthHeight);
paper.DrawRectangle(_blackPen, _rectangles[0, 0]);
}
}_rectangles[0, 0]
?Решение задачи: «Событие Click для объекта Rectangle»
textual
Листинг программы
public partial class Form1 : Form
{
const int ROW = 8;
const int COL = 8;
Rectangle[,] rect = new Rectangle[8, 8];
Rectangle mouserect; // прямоугольник для указателя мыши
Graphics picBoxGraphics;
Random rand = new Random();
public Form1()
{
InitializeComponent();
mouserect.Size = new Size(1, 1);
for (int i = 0; i < rect.GetLength(0); i++)
{
for (int j = 0; j < rect.GetLength(1); j++)
{
rect[i, j].Width = pictureBox1.Width / ROW;
rect[i, j].Height = pictureBox1.Height / COL;
rect[i, j].Location = new Point(i * rect[i, j].Width , j * rect[i, j].Height);
}
}
picBoxGraphics = pictureBox1.CreateGraphics();
}
private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
{
mouserect.Location = e.Location; // определили позицию мыши
for (int i = 0; i < rect.GetLength(0); i++)
{
for (int j = 0; j < rect.GetLength(1); j++)
{
if (rect[i, j].IntersectsWith(mouserect)) // есть ли пересечение
{
Color color = Color.FromArgb( rand.Next(256),rand.Next( 256),rand.Next( 256));
SolidBrush brush = new SolidBrush(color);
this.picBoxGraphics.FillRectangle(brush, rect[i, j]);
}
}
}
}