如何在 .NET 中创建和使用资源 [英] How to create and use resources in .NET

查看:19
本文介绍了如何在 .NET 中创建和使用资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建可以在程序的各个部分轻松引用和使用的资源?

How do I create a resource that I can reference and use in various parts of my program easily?

我的具体问题是我有一个 NotifyIcon,我想根据程序的状态更改其图标.一个常见的问题,但我一直在努力解决一个问题.

My specific problem is that I have a NotifyIcon that I want to change the icon of depending on the state of the program. A common problem, but one I've been struggling with for a long time.

推荐答案

好吧,在四处搜索并从 StackOverflow 周围拼凑各种点之后(哎呀,我已经喜欢这个地方了),大多数问题已经过了这个阶段.不过,我确实设法解决了我的问题.

Well, after searching around and cobbling together various points from around StackOverflow (gee, I love this place already), most of the problems were already past this stage. I did manage to work out an answer to my problem though.

如何创建资源:

就我而言,我想创建一个图标.这是一个类似的过程,无论您想添加什么类型的数据作为资源.

In my case, I want to create an icon. It's a similar process, no matter what type of data you want to add as a resource though.

  • 右键单击要向其添加资源的项目.在解决方案资源管理器中执行此操作.从列表中选择属性"选项.
  • 点击资源"标签.
  • 栏顶部的第一个按钮可让您选择要添加的资源类型.它应该从字符串开始.我们想添加一个图标,所以点击它并从选项列表中选择图标".
  • 接下来,移至第二个按钮添加资源".您可以添加新资源,或者如果您已经制作了一个图标,您也可以添加它.按照您选择的选项的提示进行操作.
  • 此时可以双击新添加的资源进行编辑.请注意,资源也会显示在解决方案资源管理器中,双击那里同样有效.

如何使用资源:

太好了,所以我们有了新资源,我们很想拥有那些可爱的不断变化的图标......我们该怎么做?好吧,幸运的是,C# 使这变得非常容易.

Great, so we have our new resource and we're itching to have those lovely changing icons... How do we do that? Well, lucky us, C# makes this exceedingly easy.

有一个名为 Properties.Resources 的静态类,它可以让您访问所有资源,因此我的代码最终变得如此简单:

There is a static class called Properties.Resources that gives you access to all your resources, so my code ended up being as simple as:

paused = !paused;
if (paused)
    notifyIcon.Icon = Properties.Resources.RedIcon;
else
    notifyIcon.Icon = Properties.Resources.GreenIcon;

完成!完成的!当您知道如何做时,一切都很简单,不是吗?

Done! Finished! Everything is simple when you know how, isn't it?

这篇关于如何在 .NET 中创建和使用资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆