说三道四技术文摘-感悟人生的经典句子
说三道四 > 文档快照

快速读取 TextBox 第 N 行的资料 -VB资料

HTML文档下载 WORD文档下载 PDF文档下载
快速读取 TextBox 第 N 行的资料 -VB资料
TextBox 是以 vbCr+vbLf 为分行符号, 如果我们要逐一读取 TextBox 每一行,
无非是寻找 vbCr+vbLf 的所在位置, 然后取出每一行的字串, 不过这个方法真
的不快,而且如果我们要读取第 N 行资料, 还是要从第 1、2、┅N-1 行逐一读
起, 实在麻烦。
还好 Windows API 提供有读取 TextBox 第 N 行的功能, 细节如下:

1. API 的声明:

Const EM_GETLINE = &HC4
Const EM_LINELENGTH = &HC1
Const EM_LINEINDEX = &HBB

Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (
ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As
Any) As Long
Private Declare Sub RtlMoveMemory Lib "KERNEL32" (lpvDest As Any,
lpvSource As Any, ByVal cbCopy As Long)

注:如果以上的声明放在「一般模块」底下, 应在 Const 之前加上 Public 保留
字, 并且将 Private 保留字去掉。

2. 程序范例:

Sub TB_GetLine(ByVal hWnd As Long, ByVal whichLine As Long, Line As
String)
Dim length As Long, bArr() As Byte, bArr2() As Byte, lc As Long

lc = SendMessage(hWnd, EM_LINEINDEX, whichLine, ByVal 0&)
length = SendMessage(hWnd, EM_LINELENGTH, lc, ByVal 0&)
If length > 0 Then
ReDim bArr(length + 1) As Byte, bArr2(length - 1) As Byte
Call RtlMoveMemory(bArr(0), length, 2)
Call SendMessage(hWnd, EM_GETLINE, whichLine, bArr(0))
Call RtlMoveMemory(bArr2(0), bArr(0), length)
Line = StrConv(bArr2, vbUnicode)
Else
Line = ""
End If
End Sub

' 假设要读取 Text1 第 5 行的资料
Dim S As String
Call TB_GetLine( Text1.hWnd, 5, S )
' 传回值 S 即等于到 5 行的资料
注:TextBox 的行次是从 0 起算。

备案号:鲁ICP备13029499号-2 说三道四 www.s3d4.cn 说三道四技术文摘