五笔打字通主页
如果不借助API来获取文本框的某一行的话,那就从头开始来查找回车换行符,并确认某一行的换行位置,再来确认某一行的文本内容。但要读取的行数处在textbox最后一行,那么通过这种方式效率就太低了。
想要快速提取文本框的某一行,必须要靠API才可以做的。
在此之前要先在窗体画一个文本框,文本框内容为:
张三
李四
王五
赵六
张七
同时在窗体上再画一个按钮。以下是用VB读取文本框某一行的内容的代码:
Private Const EM_GETLINE = &HC4
Private Const EM_LINELENGTH = &HC1
Private 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)
Public Sub TextBoxGetLine(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
Private Sub Command1_Click()
Dim vData As String
Dim rows As Long
rows = CInt(InputBox("请输入要读取数据的行数:", "输入"))
Call TextBoxGetLine(Text1.hWnd, rows, vData)
MsgBox vData
End Sub
运行此程序后,在弹出的输入框,输入1,输出结果是:李四 (有必要说明的是:TextBox 的起始行是从0起算)
来源:济亨网
本文链接:https://wb98.com/post/50.html