兩種方法實現VB.NET文本框
學習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