使用索引从dll获取文本

Sep*_*hrM 5 c# string dll

如何使用索引从msvp.dll和themeui.dll等Windows dll中获取字符串?在注册表或主题文件中,有一些字符串(如主题中的DisplayName)指向dll和索引号而不是真实文本.例如,我在Windows主题文件中有:DisplayName = @%SystemRoot%\ System32\themeui.dll,-2106.那么如何使用C#和.Net 4.0从这些dll中检索真正的字符串呢?

SLa*_*aks 7

你需要使用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);
    }
Run Code Online (Sandbox Code Playgroud)

  • 如果索引号为负数,则应使用其绝对值. (2认同)