Displaying Embedded Images in a WebBrowser Control
The application that I'm developing at work is built in Visual Studio 2005 and uses an embedded WebBrowser control to display some of its information (and to think: I left a web development position to get away from JavaScript and HTML). I want to display images in the browser, but I don't have a file share or a web server to store the files.
Well it turns out that you can display images stored as embedded resources in the browser using the "res:" protocol, but this only works on old Win32 resources. I had read about this in various places, but couldn't find enough information to actually get it working until yesterday, so I figured I'd share the information here (good a place as any) for future developers to benefit from my labor. Remember, this is only for Visual Studio 2005 and .NET 2.0.
First, you've got to embed the native resources into your assembly, which I thought would be the hard part, but it's not. I've adapted my procedure below from this post at the MSDN forums. The only thing that may not be obvious is that there is only native support for BMPs and ICOs; GIFs and JPGs are considered "custom" resources. To add a GIF:
- In Visual Studio, choose File -> New -> File
- Under the General node, select Native Resource Template and click Open
- In the Designer window, right-click the ResTempl1.rct node and click Add Resource
- In the Add Resource dialog, click Import...
- Find your image file and double-click it
- When prompted for a resource type, enter GIF
Generally, the format for the URL is res://[assembly file name]/[resource type]/[resource ID]
. The resource ID is expected to be prefixed by a hash symbol (#), but the hash is a special character in URLs, so it needs to be escaped as %23
. This makes your URL read like this: res://foo.dll/GIF/%23103 if your assembly is called foo.dll, your type is "GIF" and your resource ID is 103.
And there you have it. I hope this helps some other poor shlub trying to work his way through this problem.
Labels: .NET 2.0, C#, embedded resources, Programming, res: protocol, WebBrowser control, Windows Development, Windows Programming, winforms