Entries:
Comments:
Posts:

Loading User Information from Channel 9

Something went wrong getting user information from Channel 9

Latest Achievement:

Loading User Information from MSDN

Something went wrong getting user information from MSDN

Visual Studio Achievements

Latest Achievement:

Loading Visual Studio Achievements

Something went wrong getting the Visual Studio Achievements

When AutoCorrect Goes Bad

  This article showcases AutoCorrect feature of Microsoft Word 2003 and creates a sample application around it.
Dan's Blog

Difficulty: Easy
Time Required: 1-3 hours
Cost: Free
Software: Visual Basic or Visual C# Express Editions, Microsoft Word 2003
Hardware:
Download:

Video Demo

 

  

 Download the video


 

This April Fools' Day article walks you through adding entries into Microsoft Word 2003 AutoCorrect to mess with a co-worker or family member. As you might expect, this prank requires you to have physical access to your victim's computer at a time when they're not around. Luckily, it seems that the least technically inclined people are the most likely to leave their PCs unlocked for us to have fun with! As some of you probably know, AutoCorrect is a feature in Microsoft Word that, as its name states, automatically corrects text. What is does is replace misspelled words, such as "teh," which it corrects to "the" automatically as you type. Using AutoCorrect, you can add a bunch of bogus AutoCorrect entries that ought to confuse and annoy your victim. I was inspired to use AutoCorrect for an April Fools' Day prank after using it in college on a nontech-savvy friend who was borrowing my computer and assured me that my computer had a virus because Word kept "correcting" his name to Moe Sislack (The Simpsons bar keep). Here are some fun AutoCorrect entries you can add to your hapless victim's computer:

  • Replace a your victim's name with an amusing nickname, so "Dan Fernandez" becomes "Danny 'two-tone' Fernandez."
  • Replace "over" with "I see dead people" so that they'll think their PC is haunted.
  • Replace "the" with "le" to make them think they somehow changed Word's default dictionary to French.
  • Replace "Linux" with "Windows" and watch as your office Linux bigot accidentally sends an e-mail praising Linux.

If you're not sure what words to add, you can get the maximum impact by using the most popular words in the English language. Below I'll show you three different ways to add AutoCorrect entries, from requiring no code at all, to a utility created with Express, to automating adding multiple entries into AutoCorrect.

No Tech AutoCorrect

With your victim's machine unlocked, you can add AutoCorrect entries simply by opening Word and clicking "Tools > AutoCorrect Options." This will display the image below, which you can use to add AutoCorrect entries. To add an entry, type the text you want replaced in the left text box and the replacement text to the right. As you can see in the screen shot, when "c4f" in Word has been automatically replaced by "Coding4Fun."

Using Macros to Add AutoCorrect Entries

One of the nice things about Word is that it includes a Macro Recorder which you can use to record actions and see the associated VBA Macro code. To record a macro, click "Tool > Macro > Record New Macro." Enter a name in the Record Macro dialog box as shown below and click "OK."

Then simply follow the steps in the No Tech AutoCorrect section above to manually add an entry into AutoCorrect. The Macro Recorder will generate the code to add entries into AutoCorrect, which you can see by pressing ALT+F11 to bring up the Visual Basic for Applications Editor. The code below shows how adding an AutoCorrect entry is only one line of code.

AutoCorrect.Entries.Add Name:="c4f", Value:="Coding4Fun" 

Using Express to Add AutoCorrect Entries

Using Visual Basic or Visual C# Express, we can take this a step further and create a utility that can automatically upload AutoCorrect entries represented as comma-separated values like "hello, world" to replace "hello" with "world." To begin with, simply start a blank new Windows Form application in Express. To automate Word, you'll need to add a reference to the Microsoft Word 11.0 Object Library. To do this, click "Project > Add Reference" and switch to the COM Tab. Scroll down to Microsoft Word 11.0 Object Library as shown below.

Next, we'll set up our Windows Form UI by dragging and dropping a text box and having it fill the entire form. Make sure to set the Textbox MultiLine property = "True". To support opening and saving files, drag and drop the OpenFileDialog and SaveFileDialog controls onto the form. Finally, let's add a ToolStrip button and use the "Insert Standard Items" to get a classic Windows UI.

For this utility, we will only need the New, Open, Save, and Help buttons as well as two custom buttons, the first Add to AutoCorrect, another the other Remove from AutoCorrect. To make these prettier, I'm using the icons provided by IconBuffett when you register Express so that the final toolbar looks like this:

 

Our form uses some top-level variables that store a flag if the text in the text box has changed, the file name, and a generic Dictionary object that will hold the name/value pairs to be replaced.

Visual Basic

'Variables
Dim textHasChanged As Boolean = False
Dim fileName As String = "doc1.txt"
'Use to hold a list of AutoCorrect entries
Dim myAutoCorrect As New Dictionary(Of String, String

Visual C#

//Variables
private bool textHasChanged = false;
private string fileName = "doc1.txt";

//Use to hold a list of AutoCorrect entries
Dictionary<string, string> myAutoCorrect =
new Dictionary<string, string>();

Coding the New Button

When a user clicks the "New" button, we'll call the promptToSave() routine. The code below checks if the textHasChanged property is set to true, and if so, it displays a message box asking them to save with Yes or No options. If the user clicks "Yes," we'll call the Save Button click event, to prompt them to save the file.

Visual Basic

'Display a dialog to Save the text
Public Sub promptToSave()
If textHasChanged = True Then
'Display a message box asking them to save
Dim dr As DialogResult = MessageBox.Show("Do you want to save the changes to " & _
fileName & "?", "Save File", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
If dr = System.Windows.Forms.DialogResult.Yes Then
Me.SaveToolStripButton_Click("Save File", EventArgs.Empty)
End If
End If
End Sub

Visual C#

//Display a dialog to Save the text
private void promptToSave()
{
if (textHasChanged == true)
{
//Display a message box asking them to save
DialogResult dr = MessageBox.Show("Do you want to save the changes to " +
fileName + "?", "Save File", MessageBoxButtons.YesNo,
MessageBoxIcon.Warning);
if (dr == DialogResult.Yes)
{
this.saveToolStripButton_Click("Save File", EventArgs.Empty);
}
}
}

Coding the Open Button

When a user clicks the "Open" button, we display the OpenFileDialog by calling the ShowDialog() method. If the user clicks "OK" in that dialog, we'll set the file name and read in the contents of the file, in Visual Basic using My, and in Visual C# using the File class.

Visual Basic


Private Sub OpenToolStripButton_Click(ByVal sender As System.Object, 
ByVal e As System.EventArgs) Handles OpenToolStripButton.Click
'Open File Dialog
OpenFileDialog1.InitialDirectory =
My.Computer.FileSystem.SpecialDirectories.Desktop
OpenFileDialog1.FileName = fileName
If OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
fileName = OpenFileDialog1.FileName
txtWordList.Text = My.Computer.FileSystem.ReadAllText(fileName)
End If
End Sub

Visual C#
//Open document
private void openToolStripButton_Click(object sender, EventArgs e)
{
openFileDialog1.InitialDirectory = Environment.SpecialFolder.Desktop;
//Show the Open File Dialog
openFileDialog1.FileName = fileName;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
fileName = openFileDialog1.FileName;
txtWordList.Text = File.ReadAllText(fileName);
}
}

Coding the Save Button

To wrap up, we'll display the SaveFileDialog when a user clicks the "Save" button and write the file to the file system, again in Visual Basic using My and in Visual C# using use the File class.

Visual Basic


'Save Document
Private Sub SaveToolStripButton_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles SaveToolStripButton.Click

'Show the Save File Dialog
SaveFileDialog1.FileName = fileName
SaveFileDialog1.InitialDirectory =
My.Computer.FileSystem.SpecialDirectories.Desktop
If SaveFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
My.Computer.FileSystem.WriteAllText(SaveFileDialog1.FileName,
txtWordList.Text, False)
textHasChanged = False
End If
End Sub

Visual C#
//Save document
private void saveToolStripButton_Click(object sender, EventArgs e)
{
//Show the Save File Dialog
saveFileDialog1.FileName = fileName;
saveFileDialog1.InitialDirectory = Environment.SpecialFolder.Desktop.ToString();
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
File.WriteAllText(saveFileDialog1.FileName, txtWordList.Text);
textHasChanged = false;
}
}

Adding items to the AutoCorrect Dictionary Object

To add items to AutoCorrect, first we'll need to parse the text of the text box into name/value pairs and add them to the AutoCorrect dictionary object which will hold our new entries. To do this, we'll use the StringReader class and read in the contents of the text box. Note that Visual Basic 2005 now has "Using/End Using" statements which enable you to automatically dispose of resources like file handles. We then use a While loop to loop through every line in the text box and make sure the line isn't NULL. Next, we'll use the Split() method to split the contents of a line into a string array using a comma (",") as our separator. For example, if currentLine was set to "Hello, World," calling Split() would return an array where element(0) is "Hello" and element(1) is "World." Finally we call the Add method to add the key (Hello) and value (World) to the myAutoCorrect dictionary.

Visual Basic

Public Sub updateDictionary()
Dim splitKeyValues() As String
Dim currentLine As String
Using sr As New StringReader(txtWordList.Text)
'loop through each line
While True
currentLine = sr.ReadLine()
If Not (currentLine Is Nothing) Then
'split the text and add it to the AutoCorrect Dictionary
splitKeyValues = currentLine.Split(","c)
myAutoCorrect.Add(splitKeyValues(0), splitKeyValues(1))
Else 'break when we run out of lines
Exit While
End If
End While
End Using
End Sub

Visual C#

private void updateDictionary()
{
string[] splitKeyValues;
string currentLine;
using (StringReader sr = new StringReader(txtWordList.Text))
{
//loop through each line
while (true)
{
currentLine = sr.ReadLine();
if (currentLine != null)
{
//split the text and add it to the AutoCorrect Dictionary
splitKeyValues = currentLine.Split(',');
myAutoCorrect.Add(splitKeyValues[0], splitKeyValues[1]);
}
else //break when we run out of lines
break;
}
}
}

Adding AutoCorrect Entries Using the Word Object Library

Now that we have a dictionary of key/value pairs representing AutoCorrect entries, we need to add them to Word using the Microsoft Word Object Library. In this project, we'll wrap Word operations into a WordWrapperClass to encapsulate adding and removing items from AutoCorrect. The WordWrapperClass has two public methods, AddToAutoCorrect() and RemoveFromAutoCorrect(), both of which expect a key/value generic dictionary class like myAutoCorrect. Notice below that we have two imports ("using" in C#) statements at the top of the file, one for the generic dictionary collection, and the other for interoperating with Word. The first thing we do in the AddToAutoCorrect method is call the startWord() function, which creates a nonvisible instance of Microsoft Word. Next, for each of the keys in our dictionary, we get the value for a given key and call the AutoCorrect.Entries.Add(key,value) method to add the entry into Word. When we're done adding, we call the quitWord() method, which ensures the Word instance we created in the startWord() method is properly closed. One thing to note in the quitWord method is that since Visual C# doesn't support optional parameters, we explicitly declare a variable named "empty" to represent a System.Reflection.Missing.Value type.

Visual Basic

Imports System.Collections.Generic
Imports Microsoft.Office.Interop.Word

Public Class WordWrapper
Public Sub AddToAutoCorrect(ByVal entries As Dictionary(Of String, String))
Dim oWord As Application = startWord()
Dim value As String
'Loop through each entry from the dictionary
For Each key As String In entries.Keys
entries.TryGetValue(key, value) 'get the dictionary value
'***Add the AutoCorrect entry into Word***
oWord.Application.AutoCorrect.Entries.Add(key, value)
Next
quitWord(oWord) 'cleanup
End Sub

Private Function startWord() As Application
'Setup Word
Dim oWord As Application = New Application()
oWord.Visible = False
Return oWord
End Function

Private Sub quitWord(ByRef oWord As Application)
'Quit Word
oWord.Application.Quit()
End Sub
End Class

Visual C#

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Interop.Word;

public class WordWrapper
{
object empty = System.Reflection.Missing.Value;

public void AddToAutoCorrect(Dictionary<string, string> entries)
{
Application oWord = startWord();
string value;

//Loop through each entry from the dictionary
foreach (string key in entries.Keys)
{
//get the dictionary value
entries.TryGetValue(key, out value);
//***Add the AutoCorrect entry into Word***
oWord.Application.AutoCorrect.Entries.Add(key, value);
}
quitWord(oWord); //cleanup
}

private Application startWord()
{
Application oWord = new Application();
oWord.Visible = false;
return oWord;
}

private void quitWord(Application oWord)
{
//Quit Word
oWord.Application.Quit(ref empty, ref empty, ref empty);
}
}

Removing AutoCorrect Entries from the Word Object Library

All good practical jokes hopefully leave no actual harm to your hapless victim and that's why we created a way to automate removing AutoCorrect Entries. This function is similar to the AddToAutoCorrect method in that we pass in a generic Dictionary class containing key/value pairs for AutoCorrect entries. The difference here is that we have two loops, one for each Dictionary key, and another that loops through all of the AutoCorrect entries looking for matches. We need to loop through each AutoCorrect entry and verify that the key and value object match exactly those in our dictionary so that we don't delete any incorrect AutoCorrect entries. For example, we want to delete our "Hello,World" entry but don't want to fix "helo,hello," for example. If we get an exact match on the key and value, we call the AutoCorrectEntry Delete() method to remove it.

Visual Basic

Public Sub RemoveFromAutoCorrect(ByVal entries As Dictionary(Of String, String))
Dim oWord As Application = startWord()
Dim value As String

'Loop through each entry from the dictionary
For Each key As String In entries.Keys
entries.TryGetValue(key, value) 'get the dictionary value

'Loop through each Word AutoCorrect entry
For Each a As AutoCorrectEntry In oWord.AutoCorrect.Entries
'Entries must match key and value
If a.Name = key And a.Value = value Then
a.Delete() 'Delete the AutoCorrect entry
End If
Next
Next
quitWord(oWord) 'cleanup
End Sub

Visual C#

public void RemoveFromAutoCorrect(Dictionary<string, string> entries)
{
Application oWord = startWord();
string value;

//Loop through each entry from the dictionary
foreach (string key in entries.Keys)
{
entries.TryGetValue(key, out value); //get the dictionary value

//Loop through each Word AutoCorrect entry
foreach (AutoCorrectEntry a in oWord.AutoCorrect.Entries)
{
//Entries must match key and value
if (a.Name == key && a.Value == value)
{
a.Delete(); //Delete the AutoCorrect entry
}
}
}
quitWord(oWord); //cleanup
}

Conclusion

AutoCorrect is a cool feature and automatically adding entries is both a great timesaver and (hopefully) humorous practical joke on your unsuspecting victim. If you're looking to modify this sample, you could add RichTextFile support so that, in addition to just changing text, you can have typed-in text be replaced by RT Text like images, colors, tables, and more. For example, you could AutoCorrect the word "horse" to a picture of Borat from the Ali G Show. That will have to wait until next year though.

Daniel Fernandez is the Lead Product Manager for Visual Studio Express in the developer division at Microsoft.  He has been with Microsoft since July 2001, previously working as a Developer Evangelist in the Mid-Atlantic district. Prior to joining Microsoft, he worked as a developer at several consulting firms including IBM Global Services specializing in web-based and mobile application development.

 

Follow the Discussion

  • Illya FarhanaIllya Farhana

    I have problem to run my program in Excel VBA. How to run the program? How to transfer data in Excel to VB? i use VB 6.0..please try to help me..

  • Ryan DurkinRyan Durkin

    Is there any way to implement the AutoCorrect functionality from Word into a Windows Form text box?

  • venugopal.madugula@gmail.comvenugopal.​madugula@gm​ail.com

    What would be the impact on removing autotext in winword.

Remove this comment

Remove this thread

close

Comments Closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.