當圖片是 A 就要顯示 B,圖面是 B 就顯示 A把 Black 和 White 兩張圖片放進 Resources 內
圖片放進 PictureBox.Image 後就沒有辦法分辨是哪張圖片,所以在 PictureBox.Image.Tag 內駐記目前是哪張圖片
namespace ImageJudge
{
public partial class Form1 : Form
{
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 1; i <= 20; i++)
{
PictureBox pic = new PictureBox();
pic.Name = string.Format("Pic{0}",i);
// 預設是黑色背景
pic.Image = Properties.Resources.Black ;
// 把判斷條件放在 Tag Property 內
pic.Image.Tag = "Black";
pic.Click += pic_Click;
// 每五張圖片就換行
if (i % 5 == 0)
flowLayoutPanel.SetFlowBreak(pic, true);
flowLayoutPanel.Controls.Add(pic);
}
}
void pic_Click(object sender, EventArgs e)
{
PictureBox pic = sender as PictureBox;
if (pic == null) return ;
// 根據 Tag Property 來判斷目前圖片是哪張
if (pic.Image != null && pic.Image.Tag.ToString() == "Black")
{
pic.Image = Properties.Resources.White;
pic.Image.Tag = "White";
}
else
{
pic.Image = Properties.Resources.Black;
pic.Image.Tag = "Black";
}
}
}
}
- 延伸閱讀
- [C#] FlowLayoutPanel
沒有留言:
張貼留言