【发布时间】:2023-01-05 07:45:59
【问题描述】:
我正在尝试制作一个类似于记事本的程序。我想这样做,以便当您在文本框中键入内容时,打开的花括号会变成打开的和关闭的花括号。
我只需要 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 添加东西,但一切都在数组的范围之外。
【问题讨论】:
-
在 TextBox 的 KeyPress 事件处理程序中,添加
if (e.KeyChar == '{') { e.Handled = true; ((TextBoxBase)sender).SelectedText = "{}"; }-- 如果插入符应该在大括号内结束,添加.SelectionStart -= 1;-- 你显示的代码真的很麻烦