Mr. JWolf
Mr. JWolf

Reputation: 1385

Apply AutoCorrect on inserted text using Microsoft.Office.Interop.Word

When I am inserting text into Word using Microsoft.Office.Interop.Word, the inserted text will not have auto correct applied to it.

I have for example an auto correct in Word which should change auto correct to AUTO CORRECT.

string text = "is this auto correct? Is this auto format 1/2?";
int start = word.Selection.Start;
word.Selection.TypeText(text);
int end = word.Selection.Start;
Microsoft.Office.Interop.Word.Range insertedRange = word.ActiveDocument.Range(start, end);
insertedRange.AutoFormat();

// In Word the text will come over as:
// Actual:   "is this auto correct? is this auto format ½?"
// Expected: "Is this AUTO CORRECT? Is this auto format ½?"
//            ^       ^^^^ ^^^^^^^  ^

Auto format works, Word will change 1/2 to ½. But Word will not change auto correct to AUTO CORRECT.

I cannot find an a function for applying auto correct for the text I have inserted. Range does not appear to have such a function.

The closest I have come is to enumerate all the auto corrections myself and applying the auto correct if necessary see here. But this approach does not include Capitalize first letter of sentences and other such auto correct features in Word.

If I manually place my caret next to the auto correct text and press <space> the text will change to AUTO CORRECT, I need a way to trigger this from code.

How can I apply auto correct to the text I have inserted?

Upvotes: 0

Views: 223

Answers (1)

joeschwa
joeschwa

Reputation: 3175

Word's AutoCorrect functionality evaluates each keystroke as it is input to determine if what has come before needs correction. This is why typing a space or a grammar mark triggers a correction for the initial capital in a sentence or a custom AutoCorrect "Replace text as you type" rule. C# methods such as Selection.TypeText or Range.InsertAfter won't work because the individual keystrokes cannot be evaluated. However, SendKeys.Send sends individual keystrokes that can be evaluated by AutoCorrect. All that is needed is to break down the string and submit the individual characters:

using Word = Microsoft.Office.Interop.Word;

Word.Application word = Globals.ThisAddIn.Application;

string text = "is this auto correct? Is this auto format 1/2?";
int start = word.Selection.Start;
//Loop through string characters and input with SendKeys to access AutoCorrect
foreach (char c in text)
{
    SendKeys.Send(c.ToString());
}
int end = word.Selection.Start;
Range insertedRange = word.ActiveDocument.Range(start, end);
insertedRange.AutoFormat();

There will be a slight delay in the inserting of the text due to SendKeys and the AutoCorrect being called for each character, however this should not be an issue for most applications.

Upvotes: 2

Related Questions