Find cursor(not mousepointer) position in editing control

Xancholy

Well-known member
Joined
Aug 29, 2006
Messages
143
Programming Experience
Beginner
Can someone please tell me how to find the x,y coordinates of where my cursor is in an editing control like richtextbox. I don't need the mousepointer coordinates but the editor's cursor position.

I found this VB code to achieve this. How can I convert it to vb.net ? Or is there a simpler solution ?

VB.NET:
    Option Explicit
    
    Private Type POINTAPI
        X As Long
        Y As Long
    End Type

VB.NET:
'CHANGE NAME OF EDIT CONTROL IF NECESSARY
Private Sub Text1_KeyPress(KeyAscii As Integer)

    '=================================
    'This example grabs the current X and Y of a Text Cursor 
    'Position within a Text Box Control (works equally well in a 
    'Rich Text Box) and prints the Cursor's X & Y position in 
    'the Form's Title Bar
    'The Unit of Measure returned is Pixels
    'The Co-ordinates returned are from the Top and Left of the 
    'text box or RTF
    'Control's absolute position - so don't forget to add/remove 
     'the control's .left and .top co-ordinates if required.
    'If you require the Text Cursor's X and Y position in a 
    'different control (as in a Find and Replace' example, where
    'a text box contains the search criteria, but you
    'require the Cursor's position in the main Text's control), 
     'set the focus to the desired control before calling the 
    'GetTCurs...
    'i.e. insert the following
    'RichTextBox1.SetFocus
    '=================================
    Dim XPos As Long
    Dim YPos As Long
    
    XPos = GetTCursX
    YPos = GetTCursY
    '=================================
    'However, as vbTwips are the default unit of measure, you 
    'can obtain
    'the position in vbTwips using the following call
    'XPos = ScaleX(GetTCursX, vbPixels, vbTwips)
    'YPos = ScaleY(GetTCursY, vbPixels, vbTwips)
    '=================================
    Me.Caption = "X: " & XPos & " Y: " & YPos
    
End Sub

Public Function GetTCursX() As Long
    Dim pt As POINTAPI
    GetCaretPos pt
    GetTCursX = pt.X
End Function

Public Function GetTCursY() As Long
    Dim pt As POINTAPI
    GetCaretPos pt
    GetTCursY = pt.Y
End Function
 

MattP

Well-known member
Joined
Feb 29, 2008
Messages
1,206
Location
WY, USA
Programming Experience
5-10
VB.NET:
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim xyPosition As Point = RichTextBox1.GetPositionFromCharIndex(RichTextBox1.SelectionStart)

        TextBox1.Text = "X: " & xyPosition.X
        TextBox2.Text = "Y: " & xyPosition.Y
    End Sub
 
Top Bottom