.Net C# WinForm -- 获取TextBox当前焦点所在位置,插入文本,选中文本

在.Net WinForm下,有非常强大的属性可以帮助我们完成TextBox焦点的获取,它就是TextBoxBase.SelectionStart

  • 当TextBox中有文本被选中的时候,则返回选中文本的起始点索引。
  • 当没有文本被选中的时候,则放回光标所在的位置。
  • 也可以设置SelectionStart = intvaluel来改变当前光标所在位置
  • 通过设置SelectionLength可以选中从SelectionStart以后的文本

      下面看一个例子,新建一个Form,加入一个TextBox,一个Button:

      Insert按钮的代码如下:

   string strInsertText = " [Hello] ";
   int start = this.textBox1.SelectionStart;
   this.textBox1.Text = this.textBox1.Text.Insert(start,strInsertText);
   this.textBox1.Focus();
   this.textBox1.SelectionStart = start;
   this.textBox1.SelectionLength = strInsertText.Length;

posted @ 2010-10-08 10:10  deepwishly  阅读(1409)  评论(0编辑  收藏  举报