簡體   English   中英

如何在文本框中找到光標的位置? C#

[英]How do I find the position of a cursor in a text box? C#

我有一個標准的WinForms TextBox,我想在文本中的光標位置插入文本。 我怎樣才能獲得光標的位置?

謝謝

無論是否選擇任何文本, SelectionStart屬性都表示您所關注文本的索引。 所以你可以使用String.Insert注入一些文本,如下所示:

myTextBox.Text = myTextBox.Text.Insert(myTextBox.SelectionStart, "Hello world");

您想要檢查TextBoxSelectionStart屬性。

詹姆斯,當你只想在光標位置插入一些文本時,你需要替換整個字符串是非常低效的。

更好的解決方案是:

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;
    }
}

在什么事件上你會建議我記錄變量? 離開?

目前我有:

private void comboBoxWildCard_SelectedIndexChanged(object sender, EventArgs e)
{
    textBoxSt1.Focus();
    textBoxSt1.Text.Insert(intCursorPos, comboBoxWildCard.SelectedItem.ToString());

}

private void textBoxSt1_Leave(object sender, EventArgs e)
{
    intCursorPos = textBoxSt1.SelectionStart;
}

在Leave事件上錄制工作但文本沒有插入,我錯過了什么?

更新:我需要textBoxSt1.Text =

textBoxSt1.Text = textBoxSt1.Text.Insert(intCursorPos, comboBoxWildCard.SelectedItem.ToString());

謝謝大家。

謝謝

int cursorPosition = textBox1.SelectionStart;
//it will extract your current cursor position where ever it is
//textBox1 is name of your text box. you can use one
//which is being used by you in your form

要在TextBox文本中單擊鼠標時獲取插入位置,請使用TextBox MouseDown事件。 使用MouseEventArgs X和Y屬性創建一個點。 TextBox有一個名為GetCharIndexFromPosition(point) 將它傳遞給它並返回插入位置。 如果您使用鼠標確定要插入新文本的位置,則此方法有效。

您必須將SelectionStart屬性保留在變量中,然后在按下按鈕時將焦點移回TextBox。 然后將SelectionStart屬性設置為變量中的屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM