64

I have a standard WinForms TextBox and I want to insert text at the cursor's position in the text. How can I get the cursor's position?

Thanks

4

9 に答える 9

93

Regardless of whether any text is selected, the SelectionStart property represents the index into the text where you caret sits. So you can use String.Insert to inject some text, like this:

myTextBox.Text = myTextBox.Text.Insert(myTextBox.SelectionStart, "Hello world");
于 2009-02-08T22:38:19.380 に答える
15

You want to check the SelectionStart property of the TextBox.

于 2009-02-08T22:36:14.660 に答える
7

James さん、カーソル位置にテキストを挿入したいだけなのに、文字列全体を置き換える必要があるのはかなり非効率的です。

より良い解決策は次のとおりです。

textBoxSt1.SelectedText = ComboBoxWildCard.SelectedItem.ToString();

何も選択していない場合は、カーソル位置に新しいテキストが挿入されます。何かを選択している場合、選択したテキストが挿入したいテキストに置き換えられます。

私はeggheadcafeサイトからこの解決策を見つけました。

于 2009-04-16T23:10:20.457 に答える
5

あなたがしなければならないのはこれだけです:

ドキュメントのカーソル位置にテキストを挿入する項目 (ボタン、ラベルなど) をダブルクリックします。次に、これを入力します。

richTextBox.SelectedText = "whatevertextyouwantinserted";
于 2011-09-05T13:54:56.107 に答える
4

これは、最後の有効な入力テキスト位置を復元して、数字のみを入力できるようにする私の作業実現です。

Xaml:

<TextBox
      Name="myTextBox" 
      TextChanged="OnMyTextBoxTyping" />

コードビハインド:

private void OnMyTextBoxTyping(object sender, EventArgs e)
{
    if (!System.Text.RegularExpressions.Regex.IsMatch(myTextBox.Text, @"^[0-9]+$"))
    {
        var currentPosition = myTextBox.SelectionStart;
        myTextBox.Text = new string(myTextBox.Text.Where(c => (char.IsDigit(c))).ToArray());
        myTextBox.SelectionStart = currentPosition > 0 ? currentPosition - 1 : currentPosition;
    }
}
于 2014-09-25T04:53:52.553 に答える
1

のテキスト内でマウスをクリックしたときにキャレットの位置を取得するにはTextBox、イベントを使用しTextBox MouseDownます。の X プロパティと Y プロパティを使用してポイントを作成しますMouseEventArgs。にはTextBoxと呼ばれるメソッドがありGetCharIndexFromPosition(point)ます。ポイントを渡すと、キャレットの位置が返されます。これは、マウスを使用して新しいテキストを挿入する場所を決定する場合に機能します。

于 2014-05-19T00:19:49.137 に答える