我用于读取2个richtextbox内容的代码如下:
richTextBox1.Text = File.ReadAllText(tfsVersionFilePath);
richTextBox2.Text = File.ReadAllText(dbVersionFilePath);
现在,我需要比较两个富文本框内容,并突出显示两个富文本框中已更改的字符。目的是as in TFS
通过c#应用程序获得差异并突出显示字符(比较文件)。谢谢。
编辑:
int length = (richTextBox1.Text.Length > richTextBox2.Text.Length) ? richTextBox1.Text.Length : richTextBox2.Text.Length;
for (int i = 0; i < length; i++)
{
if (richTextBox1.Text[i] != richTextBox2.Text[i])
{
/* and then start your highlight selection here,
this is where some difference between the two rich
text boxes begins */
richTextBox1.Select(i, 1);
richTextBox1.SelectionColor = System.Drawing.Color.Yellow;
richTextBox1.SelectionBackColor = System.Drawing.Color.Red;
}
}
从调试中我了解到,执行特定行后,richTextBox1的Select
or或SelectionColor
orSelectionBackColor
方法指向文本光标的位置增加到7个位置。如何保持richTextBox1的光标位置?
首先感谢ArtyomZzz指出了DiffMatchPatch的重要来源!
这是一段代码,单击按钮后,它将在两个RichTextbox中绘制更改的字符。
首先下载diff-match-patchsource。(!请参见下面的更新!)从zip文件中复制“ DiffMatchPatch.cs”并复制到您的项目,并将cs文件包含在您的项目中。还将名称空间添加到您的using子句中。
using DiffMatchPatch;
namespace RTF_diff
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// this is the diff object;
diff_match_patch DIFF = new diff_match_patch();
// these are the diffs
List<Diff> diffs;
// chunks for formatting the two RTBs:
List<Chunk> chunklist1;
List<Chunk> chunklist2;
// two color lists:
Color[] colors1 = new Color[3] { Color.LightGreen, Color.LightSalmon, Color.White };
Color[] colors2 = new Color[3] { Color.LightSalmon, Color.LightGreen, Color.White };
public struct Chunk
{
public int startpos;
public int length;
public Color BackColor;
}
private void button1_Click(object sender, EventArgs e)
{
diffs = DIFF.diff_main(RTB1.Text, RTB2.Text);
DIFF.diff_cleanupSemanticLossless(diffs); // <--- see note !
chunklist1 = collectChunks(RTB1);
chunklist2 = collectChunks(RTB2);
paintChunks(RTB1, chunklist1);
paintChunks(RTB2, chunklist2);
RTB1.SelectionLength = 0;
RTB2.SelectionLength = 0;
}
List<Chunk> collectChunks(RichTextBox RTB)
{
RTB.Text = "";
List<Chunk> chunkList = new List<Chunk>();
foreach (Diff d in diffs)
{
if (RTB == RTB2 && d.operation == Operation.DELETE) continue; // **
if (RTB == RTB1 && d.operation == Operation.INSERT) continue; // **
Chunk ch = new Chunk();
int length = RTB.TextLength;
RTB.AppendText(d.text);
ch.startpos = length;
ch.length = d.text.Length;
ch.BackColor = RTB == RTB1 ? colors1[(int)d.operation]
: colors2[(int)d.operation];
chunkList.Add(ch);
}
return chunkList;
}
void paintChunks(RichTextBox RTB, List<Chunk> theChunks)
{
foreach (Chunk ch in theChunks)
{
RTB.Select(ch.startpos, ch.length);
RTB.SelectionBackColor = ch.BackColor;
}
}
}
}
刚开始,我试图将更改后的线条整体上以较浅的颜色进行着色。但是,这需要花费更多的工作,无法完成(为整个行着色,而不是仅对具有内容的部分进行着色),并且一开始就不是问题的一部分。
注意:有四种不同的差异后清除方法。哪一个最合适取决于输入和目的。我建议尝试cleanupSemanticLossless
。我添加了第三个屏幕截图,显示了此清理的工作方式
这是输出的屏幕截图:
和新版本之一:
清理后的屏幕截图
更新:消息来源似乎已经转移。这应该有帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句