2013-08-20 33 views
4

如何從使用索引的mssvp.dll和themeui.dll等windows dll獲取字符串? 在註冊表或主題文件中,有一些字符串(如主題中的DisplayName)指向一個dll和一個索引號,而不是真實的文本。例如我有: DisplayName = @%SystemRoot%\ System32 \ themeui.dll,-2106在Windows主題文件中。那麼,如何使用C#和.Net 4.0從那些DLL中檢索真正的字符串呢?使用索引從dll中獲取文本

+1

@SriramSakthivel:無;他想知道如何從DLL的字符串表中獲取字符串。他將需要P/Invoke。 – SLaks

+0

@SLaks啊,我剛纔意識到.. –

+2

使用LoadLibrary()加載DLL,LoadString()從資源表中加載字符串,FreeLibrary()再次卸載DLL。翻轉資源號碼上的標誌。訪問pinvoke.net網站獲取pinvoke聲明。 –

回答

5

您需要使用的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); 
    } 
+0

謝謝,但我有一個問題。我的索引是一個負數,如-2106,所以我不能和uint一起使用它。我試圖將其更改爲int或IntPtr,但沒有奏效。那麼如何傳遞一個負的resourceId? – SepehrM

+0

@SepehrM:嘗試一個未經檢查的轉換爲'uint'或'ushort'。 – SLaks

+0

不幸的是,沒有工作......任何其他解決方案? – SepehrM