c# - 从面板图片库加载图片到图片框

标签 c# .net winforms

我使用将多个图像添加到面板中的方式在 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);
    }
}

Sample Image is Here

最佳答案

请将您的代码替换为如下所示:

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/

相关文章:

.net - 为什么 Apple 允许在 iPhone 上使用 .NET 而不允许使用 Flash?

C# - 无法在 WinForms 的列表框中执行键值对

c# - 如何使用 WebBrowser 控件显示 XML?

c# - 检测不可变对象(immutable对象)的高效方法?

c# - Arduino 安全地使用 .net Core api?

.net - DNS GetHostEntry - 如何指定 DNS 服务器? 。网

c# - 普通旧 CLR 对象与数据传输对象

.net - DisplaySettingsChanging 上的 WPF 互操作死锁

C# HttpWebRequest - 转义 POST 内容?

c# - 用于查找 List<List<int>> 最大值的 Linq 表达式?