文本框属性为允许多行显示时,由于是软回车实现的分行,无法用split(text1.text,vbcrlf)准确地取出指定行的内容。本文利用sendmessage 系列函数,通过发送文本框消息,实现了获取包含指定字符串的行,并演示了如何获取文本框中文本总行数和任意指定行的文本内容。
'add a textbox with "multiline=true","scrollbars=2".
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 function sendmessagebynum lib "user32" _
alias "sendmessagea" (byval hwnd as long, byval wmsg as long, _
byval wparam as long, byval lparam as long) as long
private declare function sendmessagebystring lib "user32" alias _
"sendmessagea" (byval hwnd as long, byval wmsg as long, byval wparam _
as long, byval lparam as string) as long
private const em_lineindex = &hbb
private const em_getlinecount = &hba
private const em_getline = &hc4
private const em_linelength = &hc1
function getlinetext(byval txtbox as textbox, byval lineindex as long) as string '返回指定行的内容
dim lc as long, linechar as long
linechar = sendmessagebynum(txtbox.hwnd, em_lineindex, lineindex, 0)
lc = sendmessagebynum(txtbox.hwnd, em_linelength, linechar, 0) + 1
getlinetext = string(lc + 2, 0)
mid(getlinetext, 1, 1) = chr(lc and &hff)
mid(getlinetext, 2, 1) = chr(lc \ &h100)
lc = sendmessagebystring(txtbox.hwnd, em_getline, lineindex, getlinetext)
getlinetext = left(getlinetext, lc)
end function
function getlinewithstr(byval txtbox as textbox, byval mystr as string) as string
dim linecount as long, temp() as string, i as long
linecount = sendmessage(txtbox.hwnd, em_getlinecount, 0, 0) '返回行数
redim temp(1 to linecount)
for i = 1 to linecount
temp(i) = "第" & i & "行:" & getlinetext(txtbox, i - 1) '添加行号
next
getlinewithstr = join(filter(temp, mystr), vbcrlf) ' 字符串过滤
erase temp
end function
private sub command1_click()
msgbox getlinewithstr(text1, "csdn"), 0, "包含“csdn”的行"
end sub
private sub form_load()
dim a(25) as string, i as long
for i = 0 to 25
a(i) = string(50, chr(i + 97))
next
text1.text = join(a, "csdn")
end sub