Rubrik: Grafik und Font | VB-Versionen: VB2005, VB2008 | 17.09.10 |
Image aus Dll mittels FindResource auslesen Eine kleine schlanke Klasse, mit der sich ein Bild aus einer DLL-Datei anhand der Resourcen-ID auslesen und anzeigen lässt. | ||
Autor: DaveS | Bewertung: | Views: 11.947 |
ohne Homepage | System: Win2k, WinXP, Win7, Win8, Win10, Win11 | Beispielprojekt auf CD |
Mit nachfolgender Klasse lässt sich ein Bild aus einer externen DLL-Datei anhand der Resourcen-ID auslesen: egal, ob BMP oder auch JPG.
Imports System.Runtime.InteropServices Imports System.IO Public Class ImageLoader ' API-Deklarationen <DllImport("kernel32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> _ Private Shared Function FindResource(ByVal hhMod As IntPtr, _ ByVal lpID As Integer, ByVal lpType As String) As IntPtr End Function <DllImport("kernel32.dll", SetLastError:=True)> _ Private Shared Function LoadResource(ByVal hhMod As IntPtr, _ ByVal hResInfo As IntPtr) As IntPtr End Function <DllImport("kernel32.dll", SetLastError:=True)> _ Private Shared Function LockResource(ByVal hResData As IntPtr) As IntPtr End Function <DllImport("kernel32.dll", SetLastError:=True)> _ Private Shared Function SizeofResource(ByVal hhMod As IntPtr, _ ByVal hResInfo As IntPtr) As Integer End Function <DllImport("kernel32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> _ Private Shared Function LoadLibrary(ByVal lpFileName As String) As IntPtr End Function <DllImport("kernel32.dll", SetLastError:=True)> _ Private Shared Function FreeLibrary(ByVal hModule As IntPtr) As Boolean End Function ' unsere Funktion, die das Bild anhand der Resource-ID ermittelt Public Shared Function GetImageFromResource(ByVal resourceId As Integer, _ ByVal moduleName As String) As Image Dim hModule As IntPtr = LoadLibrary(moduleName) If hModule = IntPtr.Zero Then Return Nothing Dim resource As IntPtr = FindResource(hModule, resourceId, "IMAGE") If resource = IntPtr.Zero Then Return Nothing Dim rsrcid As IntPtr = LoadResource(hModule, resource) If rsrcid = IntPtr.Zero Then Return Nothing Dim memory As IntPtr = LockResource(rsrcid) If memory = IntPtr.Zero Then Return Nothing Dim size As Integer = SizeofResource(hModule, resource) Dim bytes(size - 1) As Byte Marshal.Copy(memory, bytes, 0, size) Dim memStream As New MemoryStream(bytes) FreeLibrary(hModule) Return Image.FromStream(memStream) End Function End Class
Beispielaufruf:
Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click PictureBox1.Image = ImageLoader.GetImageFromResource(5031, "imageres.dll") End Sub