我想從聊天室獲取文本。爲此,我使用Marshal類獲取字符串指針並使用Marshal.PtrToStringUni將其轉換回字符串。我的目標字符串是用越南語(UTF-8,代碼頁Windows-1258)編寫的。我無法正確顯示它(結果顯示奇怪的中文和符號)。我應該在下面的代碼中更改什麼才能正確使用?謝謝〜如何從外部應用程序獲取非ansi字符串顯示正確?
'API Declaration
Declare Auto Function SendMessage Lib "user32.dll"(ByVal hWnd As IntPtr, ByVal msg As Integer, _
ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
Declare Auto Function FindWindow Lib "user32.dll" (ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr
'Sub to get chat room text
' I already got the handle of the chat text area (RoomText)
Private Sub GetText()
'get text length
length = SendMessage(RoomText, WM_GETTEXTLENGTH, 0, 0) + 1
'Alloc memory for the buffer that receives the text
Dim Handle As IntPtr = Marshal.AllocHGlobal(length)
'send WM_GETTEXT message to the chat window
Dim NumText As Integer = SendMessage(Hwnd, WM_GETTEXT, length, Handle)
'copy the characters from the unmanaged memory to a managed string
Dim Text As String = Marshal.PtrToStringUni(Handle)
'Display the string using a textbox
TextBox1.AppendText(Text)
End Sub
P/S:在其他的努力,我試過SendMessageW和SendMessageA功能,只有SendMessageA產生的串混合了英語和問號(類似於ng?y de?p ...)。 SendMessageW返回奇怪的字符。
[MultiByteToWideChar](https://msdn.microsoft.com/en-us/library/windows/desktop/dd319072.aspx)。要理解爲什麼,請閱讀[絕對最低限度的每個軟件開發人員,積極肯定Unicode和字符集(無藉口!)](https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum -every軟件開發商,絕對-正必知 - 關於支持unicode和字符集,沒有藉口/)。 – IInspectable
@IInspectable。謝謝你的提示。 –
您正在調用SendMessageA。改爲調用SendMessageW。 –