1

我创建了一个简单的 Windows 窗体应用程序 C#,它应该显示一张图片。我正在关注这里的教程以下是 form1.cs 的代码

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void pictureBox1_Click(object sender, EventArgs e)
    {
        // Construct an image object from a file in the local directory.
        // ... This file must exist in the solution.
        Image image = Image.FromFile("Picture1.png");
        // Set the PictureBox image property to this image.
        // ... Then, adjust its height and width properties.
        pictureBox1.Image = image;
        pictureBox1.Height = image.Height;
        pictureBox1.Width = image.Width;
    }
}

图像存在于解决方案文件夹中,但运行应用程序时窗口中仍然没有显示任何内容。没有编译错误。

更新

在此处输入图像描述

现在解决了。

在此处输入图像描述

4

3 回答 3

1

如果没有完整路径,图像将不会从解决方案目录加载。它将从执行可执行文件的目录加载。当您从 Visual Studio 运行时,该目录是 Debug 或 Release 文件夹。取决于在您运行它的配置文件上。

因此,将图像放入 /bin/Debug 文件夹并再次运行您的程序。

于 2012-11-11T22:40:26.030 回答
1

确保注册了 PictureBox 单击事件处理程序。仅复制示例代码是不够的。(我只是猜测)

在此处输入图像描述

于 2012-11-11T22:44:29.420 回答
0

更好的选择是将此图像添加到项目中并执行以下两项之一:

  • 添加为资源。以后可以与强类型一起使用。
  • 在文件上设置此选项:Copy to Output Directory = Copy if newer.

在 下手动添加任何内容不是一个好习惯/bin/,因为这些文件夹是易失的,并且可以随时被 Visual Studio 擦除(通常在下一次重建时)。

于 2012-11-11T22:53:05.573 回答