我使用将多个图像添加到面板中的方式在 Windows 窗体应用程序中创建了一个图像库。现在我想将点击的图像加载到另一个图片框中。有没有人可以帮助我?
我的代码
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "JPG|*.jpg|JPEG|*.jpeg|PNG|*.png";
ofd.Multiselect = true;
DialogResult dr = ofd.ShowDialog();
if(dr==DialogResult.OK)
{
int x = 20;
int y = 20;
int maxHeight = -1;
string[] files = ofd.FileNames;
foreach (string img in files)
{
PictureBox pic = new PictureBox();
pic.Image = System.Drawing.Image.FromFile(img);
pic.SizeMode = PictureBoxSizeMode.StretchImage;
pic.Location = new System.Drawing.Point(x, y);
x += pic.Width + 10;
maxHeight = Math.Max(pic.Height, maxHeight);
if(x > this.pnlGallary.Width - 100)
{
x = 20;
y += maxHeight + 10;
}
this.pnlGallary.Controls.Add(pic);
}
}
最佳答案
请将您的代码替换为如下所示:
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "JPG|*.jpg|JPEG|*.jpeg|PNG|*.png";
ofd.Multiselect = true;
DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.OK)
{
int x = 20;
int y = 20;
int maxHeight = -1;
string[] files = ofd.FileNames;
foreach (string img in files)
{
PictureBox pic = new PictureBox();
pic.Click += new EventHandler(pictureBox_Click); // call the custom event for dynamic generated PictureBox
pic.Image = System.Drawing.Image.FromFile(img);
pic.SizeMode = PictureBoxSizeMode.StretchImage;
pic.Location = new System.Drawing.Point(x, y);
x += pic.Width + 10;
maxHeight = Math.Max(pic.Height, maxHeight);
if (x > this.pnlGallary.Width - 100)
{
x = 20;
y += maxHeight + 10;
}
this.pnlGallary.Controls.Add(pic);
}
}
并为动态生成的 PictureBox
添加通用的点击事件处理程序,如下所示
void pictureBox_Click(object sender, EventArgs e)
{
pictureBox1.Image = ((PictureBox)sender).Image;
}
关于c# - 从面板图片库加载图片到图片框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39303977/