我如何创建一个资源,我可以引用和使用在我的程序的各个部分很容易?
我的具体问题是,我有一个NotifyIcon,我想根据程序的状态更改它的图标。一个常见的问题,但我已经挣扎了很长一段时间。
我如何创建一个资源,我可以引用和使用在我的程序的各个部分很容易?
我的具体问题是,我有一个NotifyIcon,我想根据程序的状态更改它的图标。一个常见的问题,但我已经挣扎了很长一段时间。
好吧,在搜索和拼凑了StackOverflow周围的各种点之后(哎呀,我已经喜欢上这个地方了),大多数问题都已经经过了这个阶段。不过我还是找到了解决问题的办法。
如何创建资源:
在我的例子中,我想创建一个图标。这是一个类似的过程,无论您想添加什么类型的数据作为资源。
Right click the project you want to add a resource to. Do this in the Solution Explorer. Select the "Properties" option from the list. Click the "Resources" tab. The first button along the top of the bar will let you select the type of resource you want to add. It should start on string. We want to add an icon, so click on it and select "Icons" from the list of options. Next, move to the second button, "Add Resource". You can either add a new resource, or if you already have an icon already made, you can add that too. Follow the prompts for whichever option you choose. At this point, you can double click the newly added resource to edit it. Note, resources also show up in the Solution Explorer, and double clicking there is just as effective.
如何使用资源:
很好,所以我们有了新的资源,我们渴望拥有那些可爱的不断变化的图标……我们怎么做呢?好吧,幸运的是,c#让这变得非常简单。
有一个静态类叫做Properties。资源,让你访问所有的资源,所以我的代码最终像这样简单:
paused = !paused;
if (paused)
notifyIcon.Icon = Properties.Resources.RedIcon;
else
notifyIcon.Icon = Properties.Resources.GreenIcon;
完成了!完成了!只要你知道怎么做,事情就简单了,不是吗?
上述方法效果很好。
另一种方法(我假设是web)是创建你的页面。向页面添加控件。然后在设计模式转到:工具>生成本地资源。资源文件将自动出现在解决方案中,页面中的所有控件都映射到资源文件中。
要创建用于其他语言的资源,请将4个字符的语言附加到文件名的末尾,在扩展名(Account.aspx.en-US。resx Account.aspx.es-ES.resx…等等)。
要检索代码背后的特定条目,只需调用这个方法:GetLocalResourceObject([资源条目键/名称])。
The above didn't actually work for me as I had expected with Visual Studio 2010. It wouldn't let me access Properties.Resources, said it was inaccessible due to permission issues. I ultimately had to change the Persistence settings in the properties of the resource and then I found how to access it via the Resources.Designer.cs file, where it had an automatic getter that let me access the icon, via MyNamespace.Properties.Resources.NameFromAddingTheResource. That returns an object of type Icon, ready to just use.
Matthew Scharley发布的代码有内存泄漏:
paused = !paused;
if (paused)
notifyIcon.Icon = Properties.Resources.RedIcon;
else
notifyIcon.Icon = Properties.Resources.GreenIcon;
你应该Dispose() notifyIcon。图标,因为Properties.Resources. properties。SOME_ICON每次使用时都会创建一个新的图标。 这可以在日志中观察到,代码如下:
Console.WriteLine(Properties.Resources.RedIcon.GetHashCode());
Console.WriteLine(Properties.Resources.RedIcon.GetHashCode());
Console.WriteLine(Properties.Resources.RedIcon.GetHashCode());
您将在日志中看到3个不同的哈希码。这意味着它们是不同的对象。
所以,简单的解决方法是:
paused = !paused;
notifyIcon.Icon?.Dispose();
notifyIcon.Icon = paused
? Properties.Resources.RedIcon;
: Properties.Resources.GreenIcon;