在 TX Text Control 中内置了 textControl.Replace() 的方法来实现文本替换操作,然而,在某些应用中我们需要在后台代码中直接进行文本替换,而不需要显示替换对话框,本文将演示该功能的实现方法。
第一步,创建一个 Windows Forms 应用程序,然后将 TextControl 控件拖拽到 Form 上。在 TextControl 右上角的只能标签依次添加 ButtonBar、RulerBar、VerticalRuler、StatusBar,然后通过 Arrange Controls Automatically命令连接自动建立这些控件之间的关联关系。
第二步,添加MenuStrip到Form上,并添加一个替换菜单项,然后双击该菜单项以创建该菜单的点击事件处理函数,然后将以下代码粘贴到 Form1.cs 文件中
int index = 0;
private void replaceToolStripMenuItem_Click(object sender, EventArgs e){index = textControl1.Find("1", index, TXTextControl.FindOptions.NoMessageBox|TXTextControl.FindOptions.NoHighlight);
if (index != -1)
{textControl1.Selection.Start = index;textControl1.Selection.Length = "1".Length;
textControl1.InputFormat.TextColor = Color.Red;textControl1.Selection.Text = "一";
textControl1.InputFormat.TextColor = Color.Black;}else {
MessageBox.Show("已经到文档末尾,没有找到匹配的文本!");
}}private void Form1_Load(object sender, EventArgs e){this.Text = "我要将文档中的1替换为2";textControl1.ResetContents();textControl1.Selection.Text = "TX Text Control .NET for Windows Forms是一1套1免最终用户版权使用费的1功能丰富的文字处1理控件,它以可重复使用控件的1形式为开发人员提供了1Word中常用的文字处1理功能,对于需要强大且灵活的1文档处理能力的应用程序而言1,是理想的选择。";
}
最后,编译运行程序,点击替换菜单项,便可以将文档中的数字 1 ,替换为中文一。
替换前:
替换后:
源码下载: