C#调用Word拼写检查功能

来源:互联网 发布:java类构造函数 编辑:程序博客网 时间:2024/05/01 21:16

    public string ChkSpelling(string word)
    {
        System.Type wordType = System.Type.GetTypeFromProgID("Word.Application");
        object wd = System.Activator.CreateInstance(wordType);

        StringBuilder sb = new StringBuilder();
        object start = 0;
        object end = 0;

        object missing = System.Type.Missing;
        object IgnoreUppercase = true;
        object AlwaysSuggest = true;

        ((ApplicationClass)wd).Visible = false;
        ((ApplicationClass)wd).Documents.Add(ref missing, ref missing, ref missing, ref missing);
        ((ApplicationClass)wd).ActiveDocument.Range(ref start, ref end).Text = word;
        ((ApplicationClass)wd).Options.CheckGrammarWithSpelling = true;
        ((ApplicationClass)wd).Options.SuggestSpellingCorrections = true;
        ((ApplicationClass)wd).CheckSpelling(word, ref IgnoreUppercase, ref AlwaysSuggest, ref missing, ref missing,
            ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);

        if (((ApplicationClass)wd).ActiveDocument.SpellingErrors.Count > 0)
        {
            this.lblStatus.Text = "Error!!!";

            foreach (ApplicationClass Suggestion in ((ApplicationClass)wd).GetSpellingSuggestions(word, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing))
            {
                sb.AppendLine(Suggestion.Name);
            }

        }
        else
        {
            this.lblStatus.Text = "Right!!!";
        }

        ((ApplicationClass)wd).ActiveDocument.Close(ref missing, ref missing, ref missing);
        ((ApplicationClass)wd).Quit(ref missing, ref missing, ref missing);

        Marshal.ReleaseComObject(((ApplicationClass)wd));
        wd = null;

        return sb.ToString();

    }
 

原创粉丝点击