5

バックグラウンドスレッドが毎秒値を更新するWindowsフォームテキストボックスがあります。テキストボックス内にカーソルを置くと、次回の更新時に現在の位置が失われます。テキストの選択についても同じです。

私はそれをそのように解決しようとしました

    protected void SetTextProgrammatically(string value)
    {
        // save current cursor position and selection
        int start = textBox.SelectionStart;
        int length = textBox.SelectionLength;

        // update text
        textBox.Text = value;

        // restore cursor position and selection
        textBox.SelectionStart = start;
        textBox.SelectionLength = length;
    }

ほとんどの場合、うまく機能します。動作しない場合は次のようになり
ます。1)テキストボックスのテキストの最後にカーソルを置きます
。2)Shiftキーを押しながら、<-矢印キーを使用してカーソルを左に移動します
。選択が正しく機能しません。

組み合わせのように見え、カーソルSelectionStart=10SelectionLength=1自動的に位置11に移動します(私が望むように10ではありません)。

何かできることがあれば教えてください!Framework.NET2.0を使用しています。
それ以外のテキストボックスにカーソル位置を設定する方法が必要SelectionStart+SelectionLengthです。

4

3 に答える 3

4
//save position
            bool focused = textBox1.Focused;
            int start = textBox1.SelectionStart;
            int len = textBox1.SelectionLength;
            //do your work
            textBox1.Text = "duviubobioub";
            //restore
            textBox1.SelectionStart = start;
            textBox1.SelectionLength = len ;
            textBox1.Select();
于 2013-02-28T14:45:52.433 に答える
3

私は解決策を見つけました!

        // save current cursor position and selection 
        int start = textBox.SelectionStart;
        int length = textBox.SelectionLength;

        Point point = new Point();
        User32.GetCaretPos(out point);

        // update text
        textBox.Text = value;

        // restore cursor position and selection
        textBox.Select(start, length);
        User32.SetCaretPos(point.X, point.Y);

これで、正常に機能します。

于 2013-03-01T06:50:19.150 に答える
0

選択せずにテキストボックスにカーソル位置を設定するには...!

textbox1.Select(textbox1.text.length,0); /* ===> End of the textbox  */
  textbox1.Select(0,0);                    /* ===> Start of the textbox  */
于 2016-02-09T03:56:20.433 に答える