我正在处理图像查看器并遇到一个小问题。
我使用对话框将图像加载到程序中,然后将它们放入单独的图片框中。
我不知道如何对每个图片框进行onclick操作,就像点击它时我想让图像显示在一个更大的图片框中。
public partial class Form1 : Form
{
List<Bitmap> images = new List<Bitmap>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int x = 0;
openFileDialog1.Filter = "Image Files(*.jpg; *.jpeg; *.bmp)|*.jpg; *.jpeg; *.bmp";
openFileDialog1.Multiselect = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
foreach(String fileName in openFileDialog1.FileNames)
{
images.Add(new Bitmap(fileName));
PictureBox pb = new PictureBox();
Image loadedImage = Image.FromFile(fileName);
pb.SizeMode = PictureBoxSizeMode.StretchImage;
pb.Width = flowLayoutPanel1.Width;
pb.Height = 200;
pb.Image = loadedImage;
pb.MouseClick += pb_MouseClick;
flowLayoutPanel1.Controls.Add(pb);
pb.Name = "" + x;
x++;
}
}
MessageBox.Show(String.Format("{0} images loaded",images.Count),"",MessageBoxButtons.OK);
}
private void Form1_Load(object sender, EventArgs e)
{
}
void pb_MouseClick(object sender, MouseEventArgs e)
{
// handle click event
if (e.Button == MouseButtons.Left)
MessageBox.Show("Image clicked");
pbMain.Image = images[0];
pbMain.SizeMode = PictureBoxSizeMode.StretchImage;
}
}
答案 0 :(得分:3)
如果在图片框的点击处理程序中,将sender
投射到PictureBox
,就像这样:
PictureBox pb = (PictureBox)sender;
然后您不需要知道哪个具体被点击了。只需使用该引用来抓取图像并将其放在更大的框中。