学习VB.NET时,你可能会遇到VB.NET文本框问题,这里将介绍VB.NET文本框问题的解决方法,在这里拿出来和大家分享一下。VB.NET文本框没有直接提供取当前行号的功能,但我们可以有如下几种方法实现:
#t#一.用windows API函数,这也是VB的方法
先声明如下API函数,注意参数类型是用Integer,因为VB.NET的Integer是32位的:
Private Declare Function SendMessageinteger Lib "user32" Alias "SendMessageA"
(ByVal hwnd As Integer, ByVal wMsg As Integer, ByVal wParam As Integer,
ByVal lParam As Integer) As Integer Const EM_LINEFROMCHAR = &HC9
'计算文本框的当前行号
Friend Function LineNo(ByVal txthwnd As Integer) As Integer
'计算文本框的当前行号
'参数txthwnd是文本框的句柄(handle)
Try
Return Format$( SendMessageinteger(txthwnd, EM_LINEFROMCHAR, -1&, 0&) + 1, "##,###")
Catch ex As Exception
End Try
End Function
二.累加计算
通过计算累加每行字符总数是否大于插入点前总字符数,来确定当前行数。
- '不使用API函数
- Friend Function LineNo(ByVal sender As Object) As Integer
- '计算文本框的当前行号
- Try
- Dim txtbox As TextBox
- Dim charCount As Integer
- Dim i As Integer
- txtbox = CType(sender, TextBox)
- For i = 0 To txtbox.Lines.GetUpperBound(0) '计算行数
- charCount += txtbox.Lines(i).Length + 2 '一个回车符长度2
- If txtbox.SelectionStart < charCount Then
- Return i + 1
- End If
- Next
- Catch ex As Exception
- End Try
- End Function