Home » VB.Net

RichTextbox - Get the cursor line position


How to get the line number where the cursor is in a RichTextBox? I'm using VB 2010


Tim Visee

(Translated with google translate)

2 Answers Found


Answer 1

Try this.


Dim LineCurosorIsIn AsInteger = RichTextBox1.GetLineFromCharIndex(RichTextBox1.GetFirstCharIndexOfCurrentLine)





Answer 2


This is indeed the solution.

 LineCurosorIsIn AsInteger
 = RichTextBox1.GetLineFromCharIndex(RichTextBox1.GetFirstCharIndexOfCurrentLine)


When you get to warp let alone the options of the RichTextBox and a line  is too long and get into two lines. Word is the second part of the rule as a rule included. It is useful to get warp set to false!



Hi to all,
i'm creating a syntax highlighter for Silverlight 4. To implement it I'm using a custom method that formats plain text to XAML: I call it and formatted text is assigned to the RichTextBox.

Well, everything works fine and the syntax is highlighted correctly but, when I try to restore cursor position after formatting, the caret returns always at the beginning.

      // Store position
      var p = richTextBox1.Selection.Start.GetPositionAtOffset(0, LogicalDirection.Forward).GetCharacterRect(LogicalDirection.Forward).GetPoint();

      // Get Plain Text
      string xaml = proc.ParseXAML(richTextBox1.Xaml);

      // Set Formatted Text
      richTextBox1.Xaml = proc.ProcessText(xaml);

      // Restore position
      var x = richTextBox1.GetPositionFromPoint(p);
      richTextBox1.Selection.Select(x, x);

The snippet above executes when KeyUp event fires. I've also tried other implementation for restoring cursor position but nothing worked.

How can I solve this problem?
Thanks in addition,





Using Interop, I need to get a reference to the paragraph where the cursor is located.

I also need to get the cursor position in the current line (I need to know when the cursor is at the begining of a line).


I have access to the document element, and I know the Selection.Range property gives me access to the absolute position of the cursor in the document, but that's all I have.


Any ideas on how to get the values I need?




What's the difference between Cursor.HotSpot and Cursor.Position.  (The doc isn't helpful.  The doc for Cursor.HotSpot says "A Point representing the cursor hot spot.")  

Thanks,  Bob

I need to implement a RichTextBox that preserves the text cursor (caret). E.g. it should be controllable from keyboard just as usual, except for not allowing text changes.
When I set the "readonly" property to true, the caret disappears.
Any help is greatly appreciated.

Text search command in richtextbox is implemented using code:

void SearchInRTB(RichTextBox rtb, string searchFor)
            foreach (var block in rtb.Blocks)
                if (block is Paragraph)
                    Paragraph p = (Paragraph)block;
                    foreach (Run run in p.Inlines)
                        if (run.Text.ToUpper().Contains(searchFor))
                            // todo: how to select found text and scroll it to visible area



How to scroll first match into view, make it selected and put cursor to it ?


Hi. I have a richtextbox and a toolbar with colors. I want to be able to set color of the text that will be typed after current carret position. For example I have a text in red color and cursor is at the end of the typed text. Now when I click the button with black, I want next typed text to be black.  It is easy to apply color on selection using Selection.ApplyPropertyValue but this doesnt work if selection is empty. I guess I must somehow create a new section or something like that after carret position. That way it will have different foreground property. I just cant figure it out. Any ideas?
One possible problem was introduced when I was simulating multipoint mouse movement with SetPosition method. Because I have failed to generate a simulated multipoint mouse click event over a mpButton I have used button's IsMMouseOver method for deciding which mpButton receives "a mouse click" (a correct operation is launched accordingly).

However IsMMouseOver is not updated when using SetPosition. This can be reproduced for example by creating two mpButtons.
- Move mouse cursor over button 1 using real USB mouse. IsMMouseOver should return true for button1 and false for button2.
- Move mouse cursor over button 2 using SetPosition (get your coordinates beforehand). IsMMouseOver still returns true for button1 and false for button2 (should be false and true).
- Now if mouse cursor is moved using real mouse, IsMMouseOver returns correct values.

This might also affect other related methods, such as IsMMousePressed.

Also I would like suggest to get information about which multipoint mouse cursors are over mpButton. Or even better: Is certain mouse cursor over a mpButton. Now IsMMouseOver seems to only give information if any of the mouse cursors are over a mpButton.

Using SDK version 1.5. Any suggestions for performing a simulated multipoint mouse click for controls are also accepted.


(Running Wince 6.0 and R3)

Hi guys I am trying to add a particular feature to a display driver and I am getting a little stuck. In a certain scenario I need to be able to restrict the mouse position to the left portion of the screen on the x coord. Meaning that if the screen resolution is 1024 x768 i can't allow the mouse position to move passed x=512.

In my display driver cursor routine I can actually make sure that I set cursor.x to 512 if cursor.x >512. The problem is that i can move the pointer all i want in the display driver but if the OS doesn't know about it, it doesn't help since the next time the mouse is moved the OS will position it back where it thought it was supposed to be. What wince OS call can I issue to set the cursor position?


thanks all

There is something wrong with the cursor position..


I'm trying to change Keyboard Cursor position in dos console using VISUAL C++ 2008

(installed in 64bit Vista).

I think gotoxy() does not work here.

Please Help.


Is it possible to get UITestControl from mouse cursor position?

I will be thankful, if some one helps me.


Hello here is my problem:

I want to show and adornment inside the text editor. This adornment will appear when the user types a combination of keys and the adornment must appear in the position of the cursor.

At this moment I can show the adornment in the line where the cursor is allocated with the caret attribute of

the IWpfTextView object, but the adornment appears at the end of the line.

So, how do I get the exact cursor position in this line to show the adornment?



Hello here is my problem:

I want to show and adornment inside the text editor. This adornment will appear when the user types a combination of keys and the adornment must appear in the position of the cursor.

At this moment I can show the adornment in the line where the cursor is allocated with the caret attribute of

the IWpfTextView object, but the adornment appears at the end of the line.

So, how do I get the exact cursor position in this line to show the adornment?



We have developed a custom image picker solution which we integrated to the Rich Text Editor in SharePoint. This is using javascript to insert the image in the editor. The image is always appended to the end since we are using code as follows:
                var imageTag = "<img src=\"" + selectedImage + "\" />";
                editor.innerHTML = editor.innerHTML+imageTag;
Is there any way we can find the cursor position, so that I can insert the image tag in that location?

Please note that this is a rich text editor so we need to take care of the html tags when inserting the image tag at the right location.



Followed steps:

1. Keep the mouse cursor on 'Google page' search button.

2. Using the code:

Dim mouseCursorPosition As System.Drawing.Point = New System.Drawing.Point(System.Windows.Forms.Cursor.Position.X, System.Windows.Forms.Cursor.Position.Y)

Dim myTestControl As UITestControl = UITestControlFactory.FromPoint(mouseCursorPosition)

Exception Information:

{Microsoft.VisualStudio.TestTools.UITest.Extension.UITestControlNotAvailableException: The control for this action was not recorded. Additional Details: The control details were not specified. ---> Microsoft.VisualStudio.TestTools.UITest.Extension.UITestControlNotAvailableException: The control for this action was not recorded." & vbCrLf & "   at Microsoft.VisualStudio.TestTools.UITest.Framework.UITestService.GetElementFromPoint(Int32 pointX, Int32 pointY)" & vbCrLf & "   at Microsoft.VisualStudio.TestTools.UITesting.UITestControl..ctor(Point point)" & vbCrLf & "   --- End of inner exception stack trace ---" & vbCrLf & "   at Microsoft.VisualStudio.TestTools.UITesting.Playback.AddUITestControlDescriptionToException(SystemException exception, IPlaybackContext context)" & vbCrLf & "   at Microsoft.VisualStudio.TestTools.UITesting.Playback.MapAndThrowException(SystemException exception, IPlaybackContext context)" & vbCrLf & "   at Microsoft.VisualStudio.TestTools.UITesting.Playback.MapAndThrowException(SystemException exception, Boolean isSearchContext)" & vbCrLf & "   at Microsoft.VisualStudio.TestTools.UITesting.UITestControl..ctor(Point point)" & vbCrLf & "   at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.FromPoint(Point absoluteCoordinates)


This problem is not seen, if we try to get the UiTest controls on calculator aplication.


I have tried to set a WPF TextBox cursor position when it gains focus and it doesn't seem to be working.  I have tried the following:

TextBox tb = new TextBox();

tb.Text = "Some Text";

#1: tb.Select(tb.Text.Length, 0);

#2: tb.SelectionStart = tb.Text.Length;

#3: tb.CaretIndex = tb.Text.Length;

and so on and so forth.  I do believe that it is working but then something overwrites it.  I don't know what events could be overwriting this but the cursor always ends up where my mouse clicks into the box.  I want the cursor to end up at the end of my text in the TextBox.  Any ideas on this?





Salam be hame!


#include "stdafx.h"

#include <iostream>

#include <conio.h>

#include <windows.h>

usingnamespace std;

gotoxy(int x,int y){ COORD c={x,y}; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),c); }

In this code, we can set the cursor anywhere easily,
but how is it to get the location of cursor and read the screen?

How do I do equivalent of NetBeans' [Last Edit](Cntl-Q)? I.e. go to the last edited position in current project.

Here's some code from a program I am working on.  It's trying to save the mouse position so that it can be restored after a contextmenu is displayed and closed.  Without the two DEBUG statements it does not work - the mouse position moves.  With the DEBUG statements it does work.  I swear that this is true.  Does anyone have any ideas?

Thanks,  Bob

PrivateSub Form1_MouseClick(ByVal sender AsObject, ByVal e As System.Windows.Forms.MouseEventArgs) HandlesMe.MouseClick

    If e.Button = Windows.Forms.MouseButtons.Right Then
      cntxmuCell.Items.Add("Occupy Cell")
      AddHandler cntxmuCell.Closed, AddressOf cntxmuCell_Closed
      'AddHandler cntxmuCell.Click, AddressOf cntxmucell_Click
      cntxmuCell.Enabled = True
      cntxmuCell.Show(Me, e.Location)
      SavedCursorLoc.X = e.Location.X ' save cursor loc so that it can be restored when menu item is closed
      SavedCursorLoc.Y = e.Location.Y
      'tbxMouseLocSaved.Text = SavedCursorLoc.X.ToString & " / " & SavedCursorLoc.Y.ToString ' DEBUGEndIfEndSubSub cntxmuCell_Closed(ByVal sender AsObject, ByVal e As ToolStripDropDownClosedEventArgs)

    Dim temppoint As Point = Cursor.Position

    temppoint.X = SavedCursorLoc.X
    temppoint.Y = SavedCursorLoc.Y

    Cursor.Position = temppoint
    'tbxRestored.Text = Cursor.Position.X.ToString & " / " & Cursor.Position.Y.ToString ' DEBUGEndSub


When the system posts WM_MOUSEMOVE messages to a window using PostMessage(), it fills out a MSG struct with the message information as well as a timestamp and the current cursor position (in screen corodinates). The WM_MOUSEMOVE message itself contains the new cursor position mapped to the client area of the target window.

Let's say an application has a control that, when clicked, captures the mouse and on every mouse move resizes the window. Let's also say that the user moves the mouse very fast and two WM_MOUSEMOVE messages are created right after each other and posted to the window.

It might look like this in raw message format:

<01882> 002402E2 P WM_MOUSEMOVE fwKeys:MK_LBUTTON xPos:1 yPos:10 [wParam:00000001 lParam:00A20001 point:(60, 187)]
<01883> 002402E2 P WM_MOUSEMOVE fwKeys:MK_LBUTTON xPos:2 yPos:10 [wParam:00000001 lParam:00A20000 point:(61, 187)]

The application then handles the first message, looks at the cursor position in the message (which is mapped to the client area) and indicates that the mouse was moved 1 pixel horizontally into the client area. The window is then resized accordingly.

The second message is then handled, but hey, wait a second, the client cursor position, which when posted indicated it was moved 2 pixels horizontally into the client area, is no longer valid because those two pixels were calculated at the time the message was posted and the window has been moved since then. That is, instead of moving the window two pixels to the right, it should only be moved 1.

My question then is: How does Windows account for this? Does it look at the message cursor position, i.e. the position that the system stamped in the MSG struct when the message was posted, and figure things out?

If so, is there a way to override the message cursor position?




<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure