日期:2014-05-18  浏览次数:20799 次

windows应用小程序打字测试
两个文本框,第一个文本框中一串字符。 在第二个文本框中输入对应字符,若错误,以红色字体显示。

我是这样写的
C# code

private static int i;
private void richTextBox2_TextChanged(object sender, EventArgs e)
{
j=richTextBox1.Text.Length;
while(i<j)
{
if (richTextBox1.Text[i]!= richTextBox2.Text[i])
{
richTextBox2.Select(i, 1);
richTextBox2.SelectionColor = Color.Red;
}
i++;
}


这代码 运行后输入错的后再输入就抛出异常。解决不了。如何解决?

------解决方案--------------------
试试这个代码
C# code
private void richTextBox2_TextChanged(object sender, EventArgs e)
{
    int start = richTextBox2.SelectionStart;
    int m = richTextBox1.TextLength > richTextBox2.TextLength ? richTextBox2.TextLength : richTextBox1.TextLength;
    for (int i = 0; i < m; i++)
    {
        if (richTextBox1.Text[i] != richTextBox2.Text[i])
        {
            richTextBox2.Select(i, 1);
            richTextBox2.SelectionColor = Color.Red;
        }
    }
    if (richTextBox2.TextLength > richTextBox1.TextLength)
    {
        richTextBox2.Select(richTextBox1.TextLength, richTextBox2.TextLength - richTextBox1.TextLength);
        richTextBox2.SelectionColor = Color.Red;
    }
    richTextBox2.SelectionStart = start;
    richTextBox2.SelectionColor = richTextBox1.ForeColor;
}

------解决方案--------------------
C# code
        private void richTextBox2_TextChanged(object sender, EventArgs e)
        {
            Int32 iLen = richTextBox2.Text.Length;
            if (iLen > 0 && iLen < richTextBox1.Text.Length)
            {
                if (richTextBox1.Text[iLen-1] != richTextBox2.Text[iLen-1])
                {
                    richTextBox2.Select(iLen-1, 1);
                    richTextBox2.SelectionColor = Color.Red;
                    richTextBox2.SelectionLength = 0;
                    richTextBox2.SelectionStart = iLen;
                    richTextBox2.SelectionColor = Color.Black;
                }
            }
        }