C# 如何使用 Windows 窗体更改按钮上的图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8895745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 05:02:00  来源:igfitidea点击:

How do I change a image on a Button using Windows Forms?

c#winformsvisual-studio-2010image

提问by radbyx

How do I toggle between two images on a Button? I have a "Lock" and "Unlock" image I would like to use on the same button.

如何在一个 上的两个图像之间切换Button?我有一个“锁定”和“解锁”图像,我想在同一个按钮上使用。

So far I have used the property window to set a single image..

到目前为止,我已经使用属性窗口来设置单个图像。

UPDATE: Many good answers, but I should have mention that my two images is in the Property folder. How do I access them with a relative path?

更新:很多很好的答案,但我应该提到我的两个图像在属性文件夹中。如何使用相对路径访问它们?

采纳答案by Samuel Slade

You will most likely have to change the Button.Imageproperty in the code-behind. See the MSDN Documentationfor information and a sample on how to do this.

您很可能必须更改Button.Image代码隐藏中的属性。有关如何执行此操作的信息和示例,请参阅MSDN 文档

回答by clearpath

You would have to code.

你将不得不编码。

if(locked)
  Button.Image = Images.Lock;
else 
  Button.Image = Images.Unlock;

where Imagesis, say, a Resource you have created through the designer.

Images例如,您通过设计器创建的资源在哪里。

回答by zzfima

Easy:

简单:

button1.Image = System.Drawing.Image.FromFile(@"C:\Users\Administrator\Pictures\forestfloor.jpg");

P.S. Before set image, check if it exist

PS在设置图像之前,检查它是否存在

回答by jkdobariya

You can change a image of Windows Form Button using 2 Methods

您可以使用 2 种方法更改 Windows 窗体按钮的图像

Method 1 for Relative Path

相对路径的方法一

button1.Image = System.Drawing.Image.FromFile(@"C:\Users\jk\Desktop\icons\image.png");

button1.Image = Image.FromFile("C:\Users\jk\Desktop\icons\image.png");

Method 2 For Resources Image

方法二资源图片

this.button1.Image = NameSpace1.Properties.Resources.Image2.png;

you can also visit MSDN Library: ButtonBase.Image Property

您还可以访问MSDN 库:ButtonBase.Image 属性