读书人

windows应用小程序打字测试,该如何解决

发布时间: 2012-06-16 20:34:32 作者: rapoo

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

读书人网 >C#

热点推荐