我有一个System.Windows.Forms.Form,并希望在运行时更改Form.Icon以显示状态.我已经设法从项目资源加载图标:
Type type = this.GetType();
System.Resources.ResourceManager resources =
new System.Resources.ResourceManager(type.Namespace + ".Properties.Resources", this.GetType().Assembly);
this.Icon = (System.Drawing.Icon)resources.GetObject(
type.Namespace + ".Icons." + statusText + ".ico");
Run Code Online (Sandbox Code Playgroud)
但是显示的图标始终保持不变(设计时间图标).我是否必须调用方法来告知表单应用更改?我使用Form.Icon有什么问题吗?
Han*_*ant 12
我不清楚你为什么这么做.只需将图标添加到您的资源即可.项目+属性,资源选项卡,添加资源按钮上的箭头,添加现有文件.然后你在运行时就像这样使用它:
private void button1_Click(object sender, EventArgs e) {
this.Icon = Properties.Resources.Mumble;
}
Run Code Online (Sandbox Code Playgroud)
当波波是图标的名称.
如果您100%确定GetObject()不返回null,则尝试在设计器中设置Icon属性.如果它仍未显示,则图标格式出现问题.确保它没有太多的颜色,256适用于XP.
好吧,Siva和Hans在哪里:GetObject返回null,因为资源的名称不对.通过以下更改,它可以工作:
Type type = this.GetType();
System.Resources.ResourceManager resources =
new System.Resources.ResourceManager(type.Namespace + ".Properties.Resources", this.GetType().Assembly);
// here it comes, call GetObject just with the resource name, no namespace and no extension
this.Icon = (System.Drawing.Icon)resources.GetObject(statusText);
Run Code Online (Sandbox Code Playgroud)
感谢你的帮助.