获取文本框当前光标所在的行和列
<System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)> _
Public Structure HWND__
'''int
Public unused As Integer
End Structure
Partial Public Class TextBoxHelper
Const EM_LINEFROMCHAR As Integer = &HC9
Const EM_LINEINDEX As Integer = &HBB
Const EM_GETLINE As Integer = &HC4
Const EM_GETSEL As Integer = &HB0
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Ansi, EntryPoint:="SendMessageW")> _
Public Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal msg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer
End Function
''' <summary>
''' 获取指定文本框当前光标所在的行和列
''' </summary>
''' <param name="texthwnd"></param>
''' <param name="iLineX">列</param>
''' <param name="iLineY">行</param>
''' <remarks></remarks>
Public Sub GetCaretPos(ByVal texthwnd As System.IntPtr, ByRef iLineX As Long, ByRef iLineY As Long)
Dim l, l1, l2 As Integer
l = SendMessage(texthwnd, EM_LINEINDEX, -1, 0)
iLineY = SendMessage(texthwnd, EM_LINEFROMCHAR, l, 0)
iLineY += 1
iLineX = SendMessage(texthwnd, EM_GETSEL, 0, 0)
iLineX = CInt(iLineX / 2 ^ 16) - l + 1
End Sub
End Class
测试调用:
Private Sub RichTextBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles RichTextBox1.MouseDown
Dim h As New TextBoxHelper
Dim l, c As Long
h.GetCaretPos(Me.RichTextBox1.Handle, c, l)
Me.Label1.Text = String.Format("L:{0};C{1}", l, c)
End Sub