我是visual C#的新手
我想做一个门票预订系统(像在电影院),我已经创建了使用面板的座位,每个座位是40 * 40
下面是我的代码:
private void panel2_Paint(object sender, PaintEventArgs e)
{
int a, b;
for (a = 0; a <= 1; a++)
{
for (b = 0; b < 12; b++)
{
Graphics g = e.Graphics;
g.FillRectangle(new SolidBrush(Color.White), b * 40, a * 40, 40, 40);
g.DrawRectangle(new Pen(Color.Black), b * 40, a * 40, 40, 40);
}
}
}
现在,我想通过鼠标单击来更改每个座位的颜色,以显示选择了哪个座位;但到目前为止还没有成功
发布于 2012-08-11 19:11:05
您最好为每个选定的座位创建单独的控件,并处理它们的Click事件。在本例中,我向Panel
添加了24个PictureBox's
。然后,我将它们的索引放在控件的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)) ;
}
}
发布于 2012-08-11 07:41:49
无需使用Graphics
对象并直接绘制到窗体,只需在触发OnMouseClick事件时设置与所选座位相对应的控件的BackColor属性即可。
https://stackoverflow.com/questions/11912895
复制相似问题