wrong values from TextBox.SelectionStart property

  • Thread starter mosquito.dotnet
  • Start date
M

mosquito.dotnet

I am getting clearly wrong values from TextBox.SelectionStart property
in C# code. For example, if I move caret one character to right by
pressing Keys.Right, sometimes declared SelectionStart property
actually decreases, sometimes it does not change. Difference seems
always at most off by 1 but it is very irritiating.

My setup is as follows:

Textbox txtText, txtCursor;
txtText.ReadOnly = true;

//since there is no SelectionChanged event (as far as i know) I detect
likely changes in an //adhoc manner. If this contributes to the problem
and if there is a better way, please tell me.
//Note that txtText is readonly, so pressing most keys does not change
caret position and is //irrelevant

private void txtText_KeyDown(...)
{
if(e.KeyCode in [Keys.Left, Right, Down, Up])
CursorMove();
}
private void txtText_MouseDown(...)
{
CursorMove();
}

//CursorMove output cursor position
void CursorMove()
{
int pos = txtText.SelectionStart;
txtCursor.Text = "pos=" + pos;
}

Any help is greatly appreciated. Thanks ahead of time.
 
M

mosquito.dotnet

I figured it out. The problem is with listening to the TextBox.KeyDown
event. This way caret position value I get is the one BEFORE what
happens after completion of the key press, hence wrong. If I listen to
the TextBox.KeyUp event, I get accurate values. Don't make the same
mistake :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top