c#怎么用窗口显示图片

来源:这里教程网 时间:2026-02-21 16:48:25 作者:

如何使用 C# 在窗口中显示图片

在 C# 程序中,可以通过使用 System.Windows.Forms 命名空间中的控件来在窗口中显示图片。以下是实现此功能的步骤:

1. 创建一个新项目

在 Visual Studio 中创建一个新的 C# Windows 窗体应用程序。

2. 添加一个 PictureBox 控件

从工具箱中将 PictureBox 控件拖放到窗体中。PictureBox 控件用于在窗口中显示图像。

3. 为图像设置路径

在 PictureBox 控件的 Properties 窗口中,找到 ImageLocation 属性并将其设置为图像文件的路径。

4. 加载图像

在窗体加载事件中,添加以下代码以加载图像:

<code class="csharp">private void Form1_Load(object sender, EventArgs e)
{
  pictureBox1.Load(pictureBox1.ImageLocation);
}</code>

5. 调整图像大小(可选)

如果图像大小不合适,可以使用以下代码调整:

<code class="csharp">pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;</code>

此代码将调整图像大小以适合 PictureBox 控件。

6. 运行应用程序

运行应用程序以查看显示在窗口中的图像。

示例代码:

<code class="csharp">using System;
using System.Drawing;
using System.Windows.Forms;
namespace ImageDisplay
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            pictureBox1.ImageLocation = @"C:\path\to\image.jpg";
            pictureBox1.Load(pictureBox1.ImageLocation);
            pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
        }
    }
}</code>

通过遵循这些步骤,您可以使用 C# 在窗口中显示图片。

相关推荐