如何在Windows窗体(C#)中更改按钮图像?

huangapple go评论88阅读模式
英文:

How to change Button image in Windows Forms (C#)?

问题

我对C#相当新,并且正在使用Visual Studio和WinForms构建的应用程序上工作。

我有一个按钮,当点击它时,我需要更改它的图像。

bool isButtonPressed = false;
// ..
// ..
private void myButtonBtn_Click(object sender, EventArgs e)
{
    if (isButtonPressed) {
        myButton.Image = Properties.Resources.Image2; // 更改为您的第二个图像
    }
    else {
        myButton.Image = Properties.Resources.Image1; // 更改为您的第一个图像
    }
    isButtonPressed = !isButtonPressed;
}

如果您需要添加命名空间,请确保在文件的顶部添加以下命名空间:

using System.Drawing;

请确保将 Properties.Resources.Image1Properties.Resources.Image2 替换为您实际图像的资源引用。

英文:

I am pretty new to C# and working on a application built with Visual Studio and WinForms.

I have a Button and I need to change its image when it gets clicked.

bool isButtonPressed = false;
..
..
private void myButtonBtn_Click(object sender, EventArgs e)
{
    if (isButtonPressed) {
        myButton.Image = ??
    }
    else {
        myButton.Image = ??
    }
    isButtonPressed = !isButtonPressed;
}

If you can be precise on what to do with examples I'd be grateful, also saying what namespace to use if I have to add one.

答案1

得分: 3

按照以下步骤从项目资源中获取图像

  1. 在项目中添加一个名为 Images 的文件夹。
  2. 将两个图像添加到此文件夹。
  3. 右键单击项目,选择属性。
  4. 切换到左侧的资源选项卡。
  5. 从工具栏中选择第一个下拉菜单中的图像。
  6. 将图像从解决方案资源管理器拖放到图像面板中。
  7. 构建项目。

现在,您可以通过以下方式获取您的 Button 图像:

myButton.Image = Properties.Resources.Image1;

资源选项卡和图像可能如下所示:

如何在Windows窗体(C#)中更改按钮图像?

英文:

Follow these steps to get your images from project resources:

  1. Add an Images folder to your project.
  2. Add two images to this folder.
  3. Right-click your project and select Properties.
  4. Switch to the Resources tab on the left.
  5. From the toolbar select Images from the first dropdown.
  6. Drag the images from the Solution Explorer and drop to the Images panel.
  7. Build your project.

Now you can get your Button images via

myButton.Image = Properties.Resources.Image1;

Resources tab and the images may look like this:

如何在Windows窗体(C#)中更改按钮图像?

huangapple
  • 本文由 发表于 2023年5月29日 22:16:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76358096.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定