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
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
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");
You want to check the SelectionStart
property of the TextBox
.
James さん、カーソル位置にテキストを挿入したいだけなのに、文字列全体を置き換える必要があるのはかなり非効率的です。
より良い解決策は次のとおりです。
textBoxSt1.SelectedText = ComboBoxWildCard.SelectedItem.ToString();
何も選択していない場合は、カーソル位置に新しいテキストが挿入されます。何かを選択している場合、選択したテキストが挿入したいテキストに置き換えられます。
私はeggheadcafeサイトからこの解決策を見つけました。
あなたがしなければならないのはこれだけです:
ドキュメントのカーソル位置にテキストを挿入する項目 (ボタン、ラベルなど) をダブルクリックします。次に、これを入力します。
richTextBox.SelectedText = "whatevertextyouwantinserted";
これは、最後の有効な入力テキスト位置を復元して、数字のみを入力できるようにする私の作業実現です。
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;
}
}
のテキスト内でマウスをクリックしたときにキャレットの位置を取得するにはTextBox
、イベントを使用しTextBox
MouseDown
ます。の X プロパティと Y プロパティを使用してポイントを作成しますMouseEventArgs
。にはTextBox
と呼ばれるメソッドがありGetCharIndexFromPosition(point)
ます。ポイントを渡すと、キャレットの位置が返されます。これは、マウスを使用して新しいテキストを挿入する場所を決定する場合に機能します。