如何用预置文本替换输入的文本c#

时间:2017-05-06 15:00:19

标签: c# visual-studio

我正在尝试在Visual Studio中创建Windows窗体应用程序。我想要做的是当用户在RichTextBox中键入内容时,它会删除您键入的内容并将其替换为预设字母。到目前为止我所拥有的是:

private void richTextBox1_TextChanged(object sender, EventArgs e)
{
    string text = richTextBox1.Text;
    richTextBox1.Text = text.Remove(text.Length - 1, 1);
}

因此,当您键入一个字母时,它会删除它。我想要的是它添加一个预设文本的字母。所以,让我们说你有This is a test text that is reasonably long的文字。当用户键入' A'时,字母' T'而是出现了。当用户键入另一个字母时,下一个字母“' h'相反显示,依此类推,直到显示全文This is a test text that is reasonably long,然后您再也无法输入。

如果需要,可以使用以下代码:

private void button6_Click(object sender, EventArgs e)
{
    webBrowser1.Navigate(textBox1.Text);
}

private void button5_Click(object sender, EventArgs e)
{
    webBrowser1.Navigate("www.google.com");
}

private void richTextBox1_TextChanged(object sender, EventArgs e)
{
    string text = richTextBox1.Text;
    richTextBox1.Text = text.Remove(text.Length - 1, 1);
}

1 个答案:

答案 0 :(得分:0)

你可以做类似的事情。

public string longText = "This is a test text that is reasonably long";
private void RichTextBox1_TextChanged(object sender, EventArgs e)
{            
    // I don't know if the user can press enter 
    // and give you an empty string so this checks that 
    // and that richTextBox1.Text is not greater than the 
    // text you want replace with, in this case longText
    if (richTextBox1.Text.Length <= longText.Length && richTextBox1.Text.Length > 0)
    {
        string text = richTextBox1.Text;
        // removes the last character, Remove returns 
        // a new string so you have to save it somewhere
        text = richTextBox1.Text.Remove(text.Length - 1, 1);
        // here you add the character you want to replace
        text += longText[richTextBox1.Text.Length - 1];
        richTextBox1.Text = text;
    }
    else if (richTextBox1.Text.Length > longText.Length)
    {
        // this case is when the user wants to add another 
        // character but the whole text it's been already replaced
        richTextBox1.Text = richTextBox1.Text.Remove(richTextBox1.Text.Length - 1, 1);
        }
    }

如果这有助于您,请告诉我。