2011-11-23 120 views
2

我搜索了很多,但我找不到如何加载一个ID是一个字符串的资源。教程Here是好的,但不这样做。有人知道如何制作它吗?这是我的结构。我想加载PNG。如何在C#中查找资源(pinvoke)字符串资源?


enter image description here


,代码:

[DllImport("kernel32.dll", SetLastError = true)] 
static extern IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, uint dwFlags); 
[DllImport("kernel32.dll", SetLastError = true)] 
static extern IntPtr FindResource(IntPtr hModule, string lpName, string lpType); 
[DllImport("kernel32.dll")] 
static extern IntPtr FindResource(IntPtr hModule, int lpID, string lpType); 
[DllImport("kernel32.dll", SetLastError = true)] 
static extern IntPtr LoadResource(IntPtr hModule, IntPtr hResInfo); 
[DllImport("kernel32.dll", SetLastError = true)] 
static extern uint SizeofResource(IntPtr hModule, IntPtr hResInfo); 

const uint LOAD_LIBRARY_AS_DATAFILE = 0x00000002; 

void LoadSkin() { 
    IntPtr hMod = LoadLibraryEx(@"C:\Users\myuser\Desktop\skin.dll", IntPtr.Zero, LOAD_LIBRARY_AS_DATAFILE);    
    IntPtr hRes = FindResource(hMod, "BACK.PNG", "23"); 

    MessageBox.Show(hRes.ToString()); // <- 0 here. 

    uint size = SizeofResource(hMod, hRes); 
    IntPtr pt = LoadResource(hMod, hRes); 

    Bitmap bmp; 
    byte[] bPtr = new byte[size]; 
    Marshal.Copy(pt, bPtr, 0, (int) size); 
    using (MemoryStream m = new MemoryStream(bPtr)) 
     bmp = (Bitmap) Bitmap.FromStream(m); 
} 

编辑:

固定它。问题出现在FindResource的声明中。对于我来说,正确的是:

[DllImport("kernel32.dll", SetLastError = true)] 
static extern IntPtr FindResource(IntPtr hModule, string lpName, uint lpType); 
+0

无法加载'skin.dll'。它在[可以找到]的地方(http://msdn.microsoft.com/en-us/library/windows/desktop/ms682586(v = vs.85).aspx)? – vcsjones

+0

它的加载很好。问题出在FindResource中。 – blez

+1

在您的代码'< - 0 here'的代码中,指向模块加载(hMod),找不到资源(hRes)。 – vcsjones

回答

2

@ “C:\ Users \用户为myuser \桌面\ skin.dll”

显然,DLL无法加载。获得更好的诊断通过这样写的:

IntPtr hMod = LoadLibraryEx(@"C:\Users\myuser\Desktop\skin.dll", IntPtr.Zero, LOAD_LIBRARY_AS_DATAFILE); 
    if (hMod == IntPtr.Zero) throw new System.ComponentModel.Win32Exception(); 

的Win32Exception类的默认构造函数已经照顾挖开Marshal.GetLastWin32Error()错误代码和生成它相应的消息的。

未找到文件可能在这里。您必须注意Desktop文件夹,外壳实际上并不显示c:\ users \ yourname \ desktop文件夹的内容,您可以混合使用多个文件夹。当您在代码中引用该文件夹时,不会发生混合。该文件的一个可能位置是c:\ users \ public \ desktop。以正确的方式解决这个问题,确保DLL位于与主EXE相同的目录中。项目+添加现有项目,导航到该DLL,以便将其添加到您的项目中。选择它并将Copy to Output Directory属性设置为“Copy if newer”。

编辑之后:资源类型参数也会有问题。请使用“#23”或将参数类型声明为整数,以便您可以传递23.

+0

看看我的编辑。 – blez

+1

看看我的编辑。 –