C# 使用索引从dll获取文本
如何使用索引从windows dll(如mssvp.dll和themeui.dll)获取字符串? 在注册表或主题文件中,有一些字符串(如主题中的DisplayName)指向dll和索引号,而不是实际文本。例如,我有:C# 使用索引从dll获取文本,c#,string,dll,C#,String,Dll,如何使用索引从windows dll(如mssvp.dll和themeui.dll)获取字符串? 在注册表或主题文件中,有一些字符串(如主题中的DisplayName)指向dll和索引号,而不是实际文本。例如,我有: DisplayName=@%SystemRoot%\System32\themeui.dll,在windows主题文件中为-2106。那么,如何使用C#和.Net 4.0从这些DLL中检索真正的字符串呢?您需要使用p/Invoke: /// <summary>R
DisplayName=@%SystemRoot%\System32\themeui.dll,在windows主题文件中为-2106。那么,如何使用C#和.Net 4.0从这些DLL中检索真正的字符串呢?您需要使用p/Invoke:
/// <summary>Returns a string resource from a DLL.</summary>
/// <param name="DLLHandle">The handle of the DLL (from LoadLibrary()).</param>
/// <param name="ResID">The resource ID.</param>
/// <returns>The name from the DLL.</returns>
static string GetStringResource(IntPtr handle, uint resourceId) {
StringBuilder buffer = new StringBuilder(8192); //Buffer for output from LoadString()
int length = NativeMethods.LoadString(handle, resourceId, buffer, buffer.Capacity);
return buffer.ToString(0, length); //Return the part of the buffer that was used.
}
static class NativeMethods {
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false, ThrowOnUnmappableChar = true)]
internal static extern IntPtr LoadLibrary(string lpLibFileName);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false, ThrowOnUnmappableChar = true)]
internal static extern int LoadString(IntPtr hInstance, uint wID, StringBuilder lpBuffer, int nBufferMax);
[DllImport("kernel32.dll")]
public static extern int FreeLibrary(IntPtr hLibModule);
}
///从DLL返回字符串资源。
///DLL的句柄(来自LoadLibrary())。
///资源ID。
///DLL中的名称。
静态字符串GetStringResource(IntPtr句柄,uint资源ID){
StringBuilder buffer=new StringBuilder(8192);//LoadString()输出的缓冲区
int length=NativeMethods.LoadString(句柄、资源ID、缓冲区、缓冲区.Capacity);
return buffer.ToString(0,length);//返回使用的缓冲区部分。
}
静态类NativeMethods{
[DllImport(“kernel32.dll”,CharSet=CharSet.Auto,SetLastError=true,BestFitMapping=false,ThrowOnUnmappableChar=true)]
内部静态外部IntPtr加载库(字符串lpLibFileName);
[DllImport(“user32.dll”,CharSet=CharSet.Auto,SetLastError=true,BestFitMapping=false,ThrowOnUnmappableChar=true)]
内部静态外部int LoadString(IntPtr hInstance、uint wID、StringBuilder lpBuffer、int nBufferMax);
[DllImport(“kernel32.dll”)]
公共静态外部intfreelibrary(IntPtr hLibModule);
}
@SriramSakthivel:No;他想知道如何从DLL的字符串表中获取字符串。他将需要P/Invoke。@SLaks啊,我刚刚意识到..使用LoadLibrary()加载DLL,LoadString()从资源表加载字符串,FreeLibrary()再次卸载DLL。翻转资源编号上的符号。访问pinvoke.net网站获取pinvoke声明。谢谢,但我有一个问题。我的索引是一个负数,比如-2106,所以我不能将它与uint一起使用。我试着把它改成int或IntPtr,但没用。那么如何传递负的resourceId呢?@sepherm:尝试对uint
或ushort
进行未选中的强制转换。如果索引号为负数,则应使用其绝对值。