I had a developer ask me how to use Resources the other day. Honestly I had never used them for any production system and so I didn’t know. So I decided to find out. Below is the code on how to do it in WPF and then after that how you would do it in Winforms.
I borrowed a lot of this example from http://mostlytech.blogspot.com/2007/09/enumerating-xaml-baml-files-in-assembly.html. The article I link to showed how to iterate through Resources files that are in your solution with the Build Action set to Resource. I then use that to put an image on a button that alternates every time it is clicked. At http://forums.msdn.microsoft.com/en-US/wpf/thread/1bb025e8-a20a-43c4-a760-8666c63ff624/ it explains how to work with Resources that you define in the Resource tab in the Project Properties. You can also set an image directly in XAML as shown below
<Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Grid> <Button Click="Button_Click"> <Image Name="ButtonImage" Source="Images/IMG_7680.jpg" /> </Button> </Grid> </Window>
I didn’t spend as much time looking at the Winforms side of things, but here is a snippet of code that can be used. Note that I set the Build Action for the Image file to EmbeddedResource because that is what all the examples said to do. Bitmap has an overload that allows it to resolve Resource References. The name of the resource becomes <Namespace>.<Path>.<Filename>.
pictureBox1.Image = new Bitmap(typeof(Form1), "Images.IMG_7680.jpg");
Note: I use this blog to post both Personal and Technical articles. For a technical only feed use the following URL (http://bryanandnoel.spaces.live.com/category/technology/feed.rss). For a family only feed use the following URL (http://bryanandnoel.spaces.live.com/category/family/feed.rss)