Get the substring of the text by using SelectionStart - c#

I want to get the substring of the text in the RichTextBox of Windows Form when I move the cursor with arrows in the keyboard.
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
string wholeText = richTextBox1.Text;
if (wholeText.Length >0)
{
int positionBegin = richTextBox1.SelectionStart;
SelectedText = wholeText.Substring(positionBegin);
}
}
But it is incorrect. For example, I typed the sentence:
How are you doing?
I want to get the substring
you doing?
There are two ways.
One is from right to left, say I move the cursor to the end of the sentence, use left arrow to move and stop before the letter y. I got
ou doing?
Or from the left to roght, say I move the cursor to the beginning of the sentence, use right arrow to move and stop before the letter y. I got
you doing?
The case one lacks the letter y'. Case two added a white space beforey`.
I tried +1 or -1 to the index, but it generated "IndexOutOfRangeException".
Anything wrong to use SelectionStart?

Use SelectionChanged event instead of KeyDown. I will return correct substring, also it will handle mouse selections.

Related

Break line in WinForms DataGrid for special characters (instead of white spaces)

I have a WinForms DataGrid. One column takes formulas from user (like "1+55-var+4"). The content of this column could be very long so I enabled text wrapping in that column.
myGridView.Columns(5).DefaultCellStyle.WrapMode = DataGridViewTriState.True
myGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders
myGridView.Columns(5).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
That behaviour works perfectly for common text columns because the wrapping recognizes white spaces for line breaking.
But my fomula content does not have white spaces. I want that line breaks happen on special character (that means +, -, /, *) or if the column space overlaps.
Has anyone an idea? Thanks.
Assuming you don't need the text to wrap while the text box is being edited, the most straightforward solution would be to add and remove return characters yourself every time the TextBox loses focus or is resized. (Like G3nt_M3caj said) However, depending on the font figuring out exactly when and where to put returns might get messy.
Alternatively, everytime the TextBox loses focus find all of the special characters in the text and append & prepend the character with a Zero Width Space (U+200B). And everytime the textbox gains focus find and remove all Zero Width Spaces. You then don't need to even worry about the TextBox resizing.
If your making a digital button calculator, you additionally need to add the Zero Width Space before and after every special character like so:
private void ButtonClick(object sender, EventArgs e)
{ string key = ((Button)sender).Text; //A string containing the character that has been clicked.
if ( '0' <= key[0] && key[0] <= '9' ) textBox1.AppendText(key);
else textBox1.AppendText('\u200B'+ key + '\u200B');
}
On a final note, whatever you do make sure the text with Zero Width Spaces cannot be copied. It would be a nightmare to debug code that somehow got a Zero Width character in it.
EDIT: I just realized you never said you were using a TextBox inside your DataGrid. Well I think it will work either way.

How to set the Caret on the position of RightClick?

I have a RichTextBox with a SpellCheck implemented. I want to place the cursor/caret exactly where the rightclick is positioned. For example, if i have two misspelled words such as :
I belive this is wroking
and I right click on "belive", the context menu that opens is based on Wroking, because my cursor was last positioned there. To open the list of suggested words of "belive", I have to first Left click on the word, to position the caret and then RightClick.
So to make it clear, I want to automatically position the caret where my cursor is on RightClick. Is it possible to do that? Thanks in advance.
I Found a way to solve the problem, by getting the mouseposition on MouseRightButtonUp event and attributing it to a TextPointer. From there, I can select the exact Range of the current word, and then do something with it.
Point mousePoint = Mouse.GetPosition(textBox);
TextPointer current = textBox.GetPositionFromPoint(mousePoint, true);

How to find the position of a single word of text in a form C#

I'm not sure if this is possible or not. I'm interested in being able to find the (x,y) position of a word of text on a WinForm.
For example, in the picture below, I want to be able to pull the (x,y) coordinate of the upper-left hand corner of the letter H in "HERE".
I know how to get the position of textbox, so I can make a rough estimate based off of where the word "HERE" is inside the textbox, but I would like to be able to just ask the program where the word is if that is possible.
Also, if there is a way to get that position, I'd like to be able to get the length and height of the word (Basically I want to know the coordinates of the bounding box of the word "HERE" if possible)
Not sure if this matters, but the textbox is a richTextBox, and the textbox is populated from a string array in the Form1 class.
Thank you in advance!
You can use GetPositionFromCharIndex method, to get position of "HERE" within the TextBox or RichTextBox (it works for both).
As you probably know, to get position in the window you have to sum this up with position of your richTextBox. Like this:
int index = richTextBox1.Text.IndexOf("HERE");
Point textBoxLocation = richTextBox1.GetPositionFromCharIndex(index);
Point windowsLocation = new Point(richTextBox1.Location.X + textBoxLocation.X, richTextBox1.Location.Y + textBoxLocation.Y);
Console.WriteLine("Position in textbox: " + textBoxLocation.ToString());
Console.WriteLine("Position in window: " + windowsLocation.ToString());

C# Get cursor line in RichTextBox

In C#, I have a RichTextBox, and I want to get the current line of the cursor. Every answer I've found says to use:
int currentLine = richTextBox1.GetLineFromCharIndex(richTextBox1.SelectionStart);
However, richTextBox1.SelectionStart only updates when you make changes to the text. If you move the cursor with the arrow keys, it does not update (I've verified this by printing SelectionStart as I move around).
How do I get the current line of the cursor, in a way that tracks it even if you use the arrow keys to move the cursor around?
I'm using VS2012 in Win8.
Edit: terrybozzio's answer showed the problem. For anyone else with this problem, you can't put the code in richTextBox1_TextChanged. You need to put it in richTextBox1_SelectionChanged.
First you need to get selectionstart,If there isn't
any selected text, the value returned is the position of the caret(with offset in characters from the start of the text),then you call getlinefromcharindex and pass that value,place it in the selectionchanged event and even with arrow keys moving the caret position it will update:
private void richTextBox1_SelectionChanged(object sender, EventArgs e)
{
int index = richTextBox1.SelectionStart;
int line = richTextBox1.GetLineFromCharIndex(index);
label1.Text = "cursor at line " + line.ToString();
}

Windows Forms RichTextBox cursor position

I have a C# Windows Forms program that has a RichTextBox control. Whenever the text inside the box is changed (other than typing that change), the cursor goes back to the beginning.
In other words, when the text in the RichTextBox is changed by using the Text property, it makes the cursor jump back.
How can I keep the cursor in the same position or move it along with the edited text?
Thanks
You can store the cursor position before making the change, and then restore it afterwards:
int i = richTextBox1.SelectionStart;
richTextBox1.Text += "foo";
richTextBox1.SelectionStart = i;
You might also want to do the same with SelectionLength if you don't want to remove the highlight. Note that this might cause strange behaviour if the inserted text is inside the selection. Then you will need to extend the selection to include the length of the inserted text.
Be careful, if someone refreshes or changes totally the RichTextBox content, the focus method must be invoqued previously in order to move the caret:
richTextBox1.Focus();
int i = richTextBox1.SelectionStart;
richTextBox1.Text = strPreviousBuffer;
richTextBox1.SelectionStart = i;
here's a smaller one, that has the same effect. this.richTextBox1.Select(this.richTextBox1.Text.Length, 0);
That marks 0 chars at the end of the text and sets the cursor to end

Categories