我目前正在制作一个比较两个文本文件的简单 Windows 窗体应用程序。该程序将每个文本文件加载到 ListBox 中,然后突出显示它们的第一个区别。我唯一剩下的问题与垂直滚动条有关 - 每次您有一个大文本文件(大约 10000 页)时,滚动条都不允许您滚动到文档的末尾(滚动条跳回顶部到每次都没有特定的位置)。我相信这是由于我使用 DrawItem 来实现高亮效果。下面是两个代码片段,应该足以让有人指出我正确的方向,如果没有,我很乐意发布更多内容。第一个是点击“检查”按钮比较两个文本文件的代码,第二个是DrawItem:
第一个代码片段:
private void checkButton_Click(object sender, EventArgs e)
{
done = false;
one = 0;
two = 0;
try
{
var file = File.OpenText(fone.Text);
}
catch
{
MessageBox.Show("Failed to open:" + fone.Text + ".");
return;
}
try
{
var file2 = File.OpenText(ftwo.Text);
}
catch
{
MessageBox.Show("Failed to open:" + ftwo.Text + ".");
return;
}
string[] msglines;
msglines = System.IO.File.ReadAllLines(fone.Text);
foreach (string s in msglines)
{
foneBox.Items.Add(s);
if (TextRenderer.MeasureText(s, myFont).Width > one)
{
one = TextRenderer.MeasureText(s, myFont).Width;
}
}
foneBox.HorizontalExtent = one;
string[] msglines2;
msglines2 = System.IO.File.ReadAllLines(ftwo.Text);
foreach (string s in msglines2)
{
ftwoBox.Items.Add(s);
if (TextRenderer.MeasureText(s, myFont).Width > two)
{
two = TextRenderer.MeasureText(s, myFont).Width;
}
}
ftwoBox.HorizontalExtent = two;
int i = 0;
if (foneBox.Items.Count == ftwoBox.Items.Count)
{
while (i < foneBox.Items.Count)
{
if (foneBox.Items[i].ToString() == ftwoBox.Items[i].ToString())
{
i++;
}
else
{
MessageBox.Show("Files are not equal. The first difference has been highlighted.");
done = true;
index = i;
foneBox.SelectedIndex = i;
ftwoBox.SelectedIndex = i;
break;
}
if (i == foneBox.Items.Count && done==false)
{
MessageBox.Show("Files are equal.");
}
}
i = 0;
}
else
{
MessageBox.Show("Files are not equal. The files are a different size.");
}
foneBox.Focus();
ftwoBox.Focus();
}
第二个代码片段:
private void foneBox_DrawItem(object sender, DrawItemEventArgs e)
{
myColor = Color.Black;
myFont = new Font(e.Font, FontStyle.Regular);
using (Brush brush = new SolidBrush(myColor))
{
if (e.Index == index && done == true)
{
e.Graphics.FillRectangle(new SolidBrush(Color.Yellow), e.Bounds);
e.Graphics.DrawString(foneBox.Items[e.Index].ToString(), myFont, brush, e.Bounds);
}
else
{
e.DrawBackground();
e.Graphics.DrawString(foneBox.Items[e.Index].ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds);
}
}
}
任何帮助将不胜感激。谢谢你。