[英]How can i set the caret position to a specific index in passwordbox in WPF
[英]How can I find the character at my caret position?
我正在嘗試制作一個類似於記事本的程序。 我想這樣做,以便當您在文本框中鍵入內容時,打開的花括號會變成打開的和關閉的花括號。
我只需要 if 語句才能正常工作。
if(textBox1.Text[textBox1.SelectionStart] == '{')
{
//Removes the last {
textBoxList.Clear();
for(int i = 0; i < textBox1.TextLength - 2; i++)
{
textBoxList.Add(Convert.ToString(textBox1.Text[i]));
}
textBox1.Text = "";
for(int i = 0; i < textBoxList.Count; i++)
{
textBox1.Text += textBoxList[i];
}
//Adds the new curly braces
textBox1.Text += indentCurlyBraces;
//Goes inside the if
textBox1.SelectionStart = textBox1.TextLength - 2;
textBox1.ScrollToCaret();
}
此 if 語句位於文本框更改方法的內部。
我試過使用 textBox1.SelectionStart,但程序崩潰了,因為索引在textBox1 string[]
之外 我也試過減去一、二,向 SelectionStart 添加東西,但一切仍然在數組的范圍之外。
將此實用程序 class 復制到您的解決方案中:
public class TweakTextBox
{
private readonly string _addValue;
private readonly string _findValue;
private readonly TextBox _textBox;
private bool enable;
public TweakTextBox(TextBox t, string findValue, string addValue)
{
_textBox = t;
_findValue = findValue;
_addValue = addValue;
_textBox.TextChanged += TextChanged;
_textBox.PreviewKeyDown += PreviewKeyDown;
}
private void PreviewKeyDown(object? sender, PreviewKeyDownEventArgs e) // this is required to allow backspacing on "}"
{
if (e.KeyCode == Keys.Back)
enable = false; // disable the tweak in order to get the backspace working
else
enable = true; // replace the tweak functionality
}
private void TextChanged(object? sender, EventArgs e)
{
int index = _textBox.SelectionStart - 1; // find current position before char input = current SelectionStart - 1
if (index >= 0 && (enable)) // if index is valid
{
string p = _textBox.Text[index..(index + 1)]; // get last input char
if (p == _findValue) // if found char is the one specified (e.g. "{")
{
string pre = _textBox.Text[0..index]; // get all text preceding the found char
string post = _textBox.Text[(index + 1)..]; // get all text following the found char
_textBox.Text = pre + _findValue + _addValue + post; // final text is = previous text + found char + char to add + following text
_textBox.Select(index + 1, 0); // reposition the caret at the last user's position
}
}
}
}
您只需要為每個要在其中啟用該 function 的 TextBox 創建一個實例。用法示例:
public Form1()
{
InitializeComponent();
TweakTextBox tweak = new(textBox1, "{", "}"); // add this line in your Form constructor
// add here other textboxes if you want
}
我添加了 PreviewKeyDown 事件,如果按下退格鍵,該事件將禁用該功能:如果您嘗試禁用此事件並在自動添加的“}”符號后使用脫字符退格,您就會明白我添加此功能的原因。
我確信有更有效的方法來實現這一點——可能使用 WPF 我會使用不同的方法,但問題被標記為 WinForms,所以我假設你沒有使用 WPF。
另外,我沒有使用 KeyPress 事件,因為文本可能因其他原因而改變——我真的認為 TextChanged 是您想要的事件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.