您最好为每个选定的座位创建单独的控件并处理它们的 Click 事件。在此示例中,我将 24 添加PictureBox's
到Panel
. 然后我将它们的索引放在Tag
控件的属性中,并附加了一个常见的单击事件处理程序。我还使用一个Bool
数组来跟踪选定的状态。
public partial class Form1 : Form
{
bool[] selected = new bool[24];
public Form1()
{
InitializeComponent();
foreach (PictureBox pb in panel1.Controls)
{
pb.Click += new EventHandler(pictureBox_Click);
}
}
private void pictureBox_Click(object sender, EventArgs e)
{
PictureBox pb = (PictureBox)sender;
int index ;
if (int.TryParse(pb.Tag.ToString(), out index))
{
if (selected[index])
{
selected[index] = false;
pb.BackColor = Color.White;
}
else
{
selected[index] = true;
pb.BackColor = Color.Red;
}
}
}
}
如果您创建一个布尔数组来存储座椅的状态,您可以使用您所拥有的,使用面板的 MouseDown 事件来设置变量并使与您的座椅相关的屏幕矩形无效。
像这样的东西。
public partial class Form1 : Form
{
bool[,] selected = new bool[2,12];
public Form1()
{
InitializeComponent();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
int a, b;
for (a = 0; a <= 1; a++)
{
for (b = 0; b < 12; b++)
{
if (selected[a, b])
{
e.Graphics.FillRectangle(new SolidBrush(Color.Red), b * 40, a * 40, 40, 40);
}
else
{
e.Graphics.FillRectangle(new SolidBrush(Color.White ), b * 40, a * 40, 40, 40);
}
e.Graphics.DrawRectangle(new Pen(Color.Black), b * 40, a * 40, 40, 40);
}
}
}
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
int xPos, yPos;
xPos = e.X / 40;
yPos = e.Y / 40;
if ((xPos > 11) || (yPos > 1)) return;
if(selected[yPos,xPos])
selected[yPos, xPos] = false;
else
selected[yPos, xPos] = true;
((Panel)sender).Invalidate(new Rectangle(xPos * 40,yPos *40,40,40)) ;
}
}