I am struggling to move the caret in a textbox editing control within a DataGridView, one line up and one line down, just as a user would get when pressing up and down arrows.
So I don't mean lines as what is between newline characters, I mean lines as what is between the left and right side of a textbox.
I cannot use GetCharIndexFromPosition and GetPositionFromCharIndex because not all text will always be shown in the textbox display area.
Edit: I cannot simulate KeyPress because I am dealing with a textbox cell within a DataGridView. My aim is in fact getting arrow keys to do what they would do in a normal textbox, instead of jumping from row to row.
This should work.
I don't think it's the cleanest solution though. Maybe you should look into the DataGridView properties/key handling.
The methods
GetPositionFromCharIndex()
andGetCharIndexFromPosition()
have two limitations:TextBox.SelectionStart
is the same for a caret at the end of a line and for a caret at the beginning of next line.To correct this, you can:
Another problem I encountered is that
TextBox.Lines
refers to logic lines separated by new-line characters, while functionsTextBox.GetLineFromCharIndex()
andTextBox.GetFirstCharIndexFromLine()
refer to visual lines as they are displayed in the textbox (that is, from side to side of TextBox, without there having to be new-line characters). Do not mix them up.Resulting code (ugly as you may claim, but working) is as follows:
Credit for the idea goes to this answer, and you may also want to take a look at MSDN reference on GetCaretPos and other Caret functions.