调用Select后,.NET TextBox不会更新SelectedText值

时间:2013-11-06 07:04:33

标签: c# .net winforms textbox

我在C#中编写了一个基于.NET Winforms的程序,我使用Select()方法以编程方式在TextBox中选择文本。我可以在屏幕上看到所选文字,SelectionLength成员会报告所选字符的准确数量,但SelectedText成员不包含任何文字:

int indexPeriod = strLectureText.IndexOfAny(terminators, indexStart);

thisTextbox.Focus();

if (indexPeriod > -1)
{
    thisTextbox.Select(indexStart, (indexPeriod - indexStart) + 1);
}
else
{
    thisTextbox.Select(indexStart, thisTextbox.Text.Length);
}

Log.Debug("jtext len=" + thisTextbox.SelectionLength + " txt=" + thisTextbox.SelectedText);
thisTextbox.ScrollToCaret();

发生了什么事?

2013年11月16日更新

我按@KingKing的请求添加了额外的代码:

delegate void delegateMoveToNextTextFragment(ref TextBox thisTextbox, char[] terminators);
private void MoveToNextTextFragment(ref TextBox thisTextbox, char[] terminators)
{
 string strLectureText = String.Empty;

 strLectureText = thisTextbox.Text;
 int currentStartPos = thisTextbox.SelectionStart + thisTextbox.SelectionLength - 1

 // search the rest of the buffer after the currently-selected string to find the next period
 int skipLastChar = 0;

 // don't include last selected character in search
 try
 {
      if ((thisTextbox.SelectionLength > 0) & (strLectureText[currentStartPos] != '.'))
  {
       skipLastChar = 1;
  }
 }
 catch (Exception ex)
 {
      Debug.WriteLine("exception caught! ex=" + ex.Message);
  skipLastChar = 0;
 }

 int indexStart = 0;

 if (currentStartPos == 0)
 {
      indexStart = 0;
 }
 else
 {
      indexStart = currentStartPos + 1;
 }

 int indexPeriod = strLectureText.IndexOfAny(terminators, indexStart);

 if (indexPeriod > -1)
 {
      thisTextbox.Select(indexStart, (indexPeriod - indexStart) + 1);
 }
 else
 {
      thisTextbox.Select(indexStart, thisTextbox.Text.Length);
 }

 thisTextbox.Focus();
 Log.Debug("jtext len=" + thisTextbox.SelectionLength + " txt=" + thisTextbox.SelectedText);
 thisTextbox.ScrollToCaret();

}

0 个答案:

没有答案