Domanda

I'm trying to add images to my tree nodes (ImageList.Add()), but just can't figure out a nice way of doing it.

I've read from MSDN help I should use System.Drawing.Image.FromFile(path). But cannot just get a file somewhere. I'm building a DLL, and want it to be a single file, no bitmaps being copied together with it.

So I've read I should add Image files to the project and mark them with Build Action as "Resource". Ok, but where do I get them??? I saw people using it in XAML files, but I don't have that.

Saw people using Resources.SomeName, but can't find those Resources class.

So....How do I do it?? I've got the files marked as resources, just need to add them to the ImageList.

By the way, I'd love to use the path relative to the Code File that is adding the images to the ImageList. But if not possible, just relative to the assembly root.

È stato utile?

Soluzione

If you want to use file paths, for items that are in your project, you must set the "Copy to Output Directory" property to "Copy Always" or "Copy if newer", otherwise it won't be in the bin folder, and then you'll be trying to pass a path to a file that doesn't exist. Build action isn't all that important in this scenario.

If you want to use compiled resources, and reference them via the Resources object, see the rest of my answer. I assume you are using Visual Studio, 2005 or later.

To add an image as a compiled resource to a clean Windows Forms project, so that you can access it via Resources.SomeName do the following:

  1. In Solution Explorer, under the windows forms project (mine is called WinFormsApplication1), expand the "Properties" folder. By default this folder should contain: AssemblyInfo.cs, Resources.resx, Settings.settings.
  2. Double-click on the Resources.resx file. This will open an editor for it. You'll probably see a table of strings, with columns "Name", "Value", "Comment".
  3. Click the drop-down arrow on the "Add Resource" button, and select "Existing File", which will allow you to browse to the image you want to add.
  4. You should now see the image appear in a gallery of sorts. Mine has the name TestImage

Now when you edit the code (mine is Fom1.cs), I can access the image as a System.Drawing.Bitmap as Properties.Resources.TestImage.

To my mind, this is the best way to do images that you want compiled into the application. If you want user-added images, you'll need to use OpenFileDialog, or something like that to get your file path. Then the Image.FormFile() will be what you want.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top