VB6.0可声明一个Object 数据类型,使用它的Charset属性为"UTF8",可解决TextBox控件中UTF8文本显示乱码问题。
Object 数据类型,Object 变量存储为 32 位(4
个字节)的地址形式,其为对象的引用。利用 Set 语句,声明为 Object
的变量可以赋值为任何对象的引用。
Charset 属性,设置或者返回字体中所用字符集。
实现代码:
Private Sub Command1_Click() '打开UTF-8文本
Dim Ados As Object
CommonDialog1.FileName = ""
CommonDialog1.Filter = "文本文件(*.txt)|*.txt|"
CommonDialog1.Action = 1
str = CommonDialog1.FileName
Set Ados = CreateObject("adodb.stream")
With Ados
.Charset = "utf-8"
.Type = 2
.Open
.LoadFromFile str
Text1.Text = .ReadText
.Close
End With
Set Ados = Nothing
End Sub
'-----------UTF8转Unicode编码
Private Declare Function MultiByteToWideChar Lib "kernel32" (ByVal CodePage As Long, ByVal dwFlags As Long, ByRef lpMultiByteStr As Any, ByVal cchMultiByte As Long, ByVal lpWideCharStr As Long, ByVal cchWideChar As Long) As Long
Private Const CP_UTF8 = 65001
'Purpose:Convert Utf8 to Unicode
Public Function UTF8_Decode(ByVal sUTF8 As String) As String
Dim lngUtf8Size As Long
Dim strBuffer As String
Dim lngBufferSize As Long
Dim lngResult As Long
Dim bytUtf8() As Byte
Dim n As Long
If LenB(sUTF8) = 0 Then Exit Function
On Error GoTo EndFunction
bytUtf8 = StrConv(sUTF8, vbFromUnicode)
lngUtf8Size = UBound(bytUtf8) + 1
On Error GoTo 0
lngBufferSize = lngUtf8Size * 2
strBuffer = String$(lngBufferSize, vbNullChar)
'Translate using code page 65001(UTF-8)
lngResult = MultiByteToWideChar(CP_UTF8, 0, bytUtf8(0), _
lngUtf8Size, StrPtr(strBuffer), lngBufferSize)
'Trim result to actual length
If lngResult Then
UTF8_Decode = Left$(strBuffer, lngResult)
End If
EndFunction:
End Function
'把你上面获取的内容转一下就行,比如Text1.Text=UTF8_Decode(strResponse)
还可以加多一句InStr(1, strResponse, "charset=utf-8") > 0判断是否是UTF8编码再执行,不是UTF8的就直接显示。 还有些网页编码那里是大写的,要这样写InStr(1, strResponse, "charset=UTF-8") > 0
一般遇到这种问题有以下几种情况:
1.调用文件参数不正确(可以多试几次调用程序的参数类型)
2.调用文件返回值不正确(逐步调试)
3.子函数参数类型不正确。
总之一步一步的进行调试,看看究竟是哪一步出错就可以了。