我正在创建一个C#窗体表单应用程序,我想在当前打开的word文档中搜索一个字符串,如果匹配,我想突出显示word文档中的文本。另外,我想知道是否可以在单词文档侧显示消息框,显示消息?
以下是我编写的代码
string matchString = "This is the text I want to match";
public void testMethod()
{
Object wordObject = null;
Application word = null;
object missObj = Missing.Value;
object readOnly = false;
object FullPath = null;
Document document = null;
try
{
wordObject = (Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
word = (Application)wordObject;
word.Visible = true;
//word.ScreenUpdating = false;
FullPath = word.ActiveDocument.FullName;
document = word.Documents.Open(ref FullPath, ref missObj, ref readOnly, ref missObj, ref missObj, ref missObj, ref missObj, ref missObj, ref missObj, ref missObj, ref missObj, ref missObj, ref missObj, ref missObj, ref missObj, ref missObj);
document.Activate();
foreach (Microsoft.Office.Interop.Word.Range docRange in document.Sentences)
{
string xx = docRange.Text.Trim();
if (docRange.Text.Trim().Equals(matchString,
StringComparison.CurrentCultureIgnoreCase))
{
docRange.HighlightColorIndex =
Microsoft.Office.Interop.Word.WdColorIndex.wdDarkYellow;
docRange.Font.ColorIndex =
Microsoft.Office.Interop.Word.WdColorIndex.wdBlue;
}
}
}
catch (Exception ex)
{
Console.Write(ex.ToString());
}
}