<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" media="screen" href="/styles/xslt/rss.xslt"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:media="http://search.yahoo.com/mrss/" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:c9="http://channel9.msdn.com">
<channel>
	<title>Comment Feed for Channel 9 - When AutoCorrect Goes Bad</title>
	<atom:link rel="self" type="application/rss+xml" href="http://channel9.msdn.com/coding4fun/articles/When-AutoCorrect-Goes-Bad/RSS"></atom:link>
	<image>
		<url>http://ecn.channel9.msdn.com/o9/c4f/images/912524_100.jpg</url>
		<title>Channel 9 - When AutoCorrect Goes Bad</title>
		<link></link>
	</image>
	<description>



&amp;nbsp;
This article showcases AutoCorrect feature of Microsoft Word 2003 and creates a sample application around it.



Dan Fernandez
Dan&#39;s Blog

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

C# Download
VB Download






Video Demo 
&amp;nbsp; 
&amp;nbsp;&amp;nbsp; 
&amp;nbsp;Download
 the video 

&amp;nbsp; 
This April Fools&#39; 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&#39;s computer at
 a time when they&#39;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 &amp;quot;teh,&amp;quot; which it corrects to &amp;quot;the&amp;quot; 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&#39; 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 &amp;quot;correcting&amp;quot; his name to Moe Sislack (The Simpsons
 bar keep). Here are some fun AutoCorrect entries you can add to your hapless victim&#39;s computer:
 


Replace a your victim&#39;s name with an amusing nickname, so &amp;quot;Dan Fernandez&amp;quot; becomes &amp;quot;Danny &#39;two-tone&#39; Fernandez.&amp;quot;


Replace &amp;quot;over&amp;quot; with &amp;quot;I see dead people&amp;quot; so that they&#39;ll think their PC is haunted.


Replace &amp;quot;the&amp;quot; with &amp;quot;le&amp;quot; to make them think they somehow changed Word&#39;s default dictionary to French.


Replace &amp;quot;Linux&amp;quot; with &amp;quot;Windows&amp;quot; and watch as your office Linux bigot accidentally sends an e-mail praising Linux.


If you&#39;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&#39;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&#39;s machine unlocked, you can add AutoCorrect entries simply by opening Word and clicking &amp;quot;Tools &amp;gt; AutoCorrect Options.&amp;quot; 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 &amp;quot;c4f&amp;quot; in Word has been automatically replaced by &amp;quot;Coding4Fun.&amp;quot;
 

 
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 &amp;quot;Tool &amp;gt; Macro &amp;gt; Record New Macro.&amp;quot; Enter a name in the Record Macro dialog
 box as shown below and click &amp;quot;OK.&amp;quot;  

 
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&amp;#43;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:=&amp;quot;c4f&amp;quot;, Value:=&amp;quot;Coding4Fun&amp;quot;&amp;nbsp;

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 &amp;quot;hello, world&amp;quot; to replace &amp;quot;hello&amp;quot; with &amp;quot;world.&amp;quot; To begin
 with, simply start a blank new Windows Form application in Express. To automate Word, you&#39;ll need to add a reference to the Microsoft Word 11.0 Object Library. To do this, click &amp;quot;Project &amp;gt; Add Reference&amp;quot; and switch to the COM Tab. Scroll down to Microsoft
 Word 11.0 Object Library as shown below.  




 
Next, we&#39;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 = &amp;quot;True&amp;quot;. To support opening and saving files, drag and drop the OpenFileDialog and
 SaveFileDialog controls onto the form. Finally, let&#39;s add a ToolStrip button and use the &amp;quot;Insert Standard Items&amp;quot; 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&#39;m using the icons provided by IconBuffett
 when you register Express so that the final toolbar looks like this:  
&amp;nbsp;
 
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  

&#39;VariablesDim textHasChanged As Boolean = FalseDim fileName As String = &amp;quot;doc1.txt&amp;quot;&#39;Use to hold a list of AutoCorrect entriesDim myAutoCorrect As New Dictionary(Of String, String)&amp;nbsp;




Visual C#  

//Variables
private bool textHasChanged = false;private string fileName = &amp;quot;doc1.txt&amp;quot;;//Use to hold a list of AutoCorrect entriesDictionary&amp;lt;string, string&amp;gt; myAutoCorrect =    new Dictionary&amp;lt;string, string&amp;gt;();



Coding the New Button  
When a user clicks the &amp;quot;New&amp;quot; button, we&#39;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 &amp;quot;Yes,&amp;quot; we&#39;ll call the
Save Button click event, to prompt them to save the file.  
Visual Basic  

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




Visual C#  
 

//Display a dialog to Save the textprivate void promptToSave(){if (textHasChanged == true)   {       //Display a message box asking them to save       DialogResult dr = MessageBox.Show(&amp;quot;Do you want to save the changes to &amp;quot; &amp;#43;           fileName &amp;#43; &amp;quot;?&amp;quot;, &amp;quot;Save File&amp;quot;, MessageBoxButtons.YesNo,            MessageBoxIcon.Warning);      if (dr == DialogResult.Yes)       {          this.saveToolStripButton_Click(&amp;quot;Save File&amp;quot;, EventArgs.Empty);       }}}Coding the Open Button 

When a user clicks the &amp;quot;Open&amp;quot; button, we display the OpenFileDialog by calling the
ShowDialog() method. If the user clicks &amp;quot;OK&amp;quot; in that dialog, we&#39;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&#39;Open File DialogOpenFileDialog1.InitialDirectory =       My.Computer.FileSystem.SpecialDirectories.DesktopOpenFileDialog1.FileName = fileNameIf OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK ThenfileName = OpenFileDialog1.FileName     txtWordList.Text = My.Computer.FileSystem.ReadAllText(fileName)End IfEnd Sub
Visual C# 


//Open documentprivate 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&#39;ll display the SaveFileDialog when a user clicks the &amp;quot;Save&amp;quot; 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  


&#39;Save DocumentPrivate Sub SaveToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveToolStripButton.Click&#39;Show the Save File Dialog   SaveFileDialog1.FileName = fileName   SaveFileDialog1.InitialDirectory =           My.Computer.FileSystem.SpecialDirectories.DesktopIf SaveFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK ThenMy.Computer.FileSystem.WriteAllText(SaveFileDialog1.FileName,          txtWordList.Text, False)      textHasChanged = FalseEnd IfEnd SubVisual C# 


//Save documentprivate 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&#39;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&#39;ll use the
StringReader class and read in the contents of the text box. Note that Visual Basic 2005 now has &amp;quot;Using/End Using&amp;quot; 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&#39;t NULL. Next, we&#39;ll use the
Split() method to split the contents of a line into a string array using a comma (&amp;quot;,&amp;quot;) as our separator. For example, if
currentLine was set to &amp;quot;Hello, World,&amp;quot; calling Split() would return an array where
element(0) is &amp;quot;Hello&amp;quot; and element(1) is &amp;quot;World.&amp;quot; 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)        &#39;loop through each line        While True            currentLine = sr.ReadLine()                If Not (currentLine Is Nothing) Then                &#39;split the text and add it to the AutoCorrect Dictionary                    splitKeyValues = currentLine.Split(&amp;quot;,&amp;quot;c)                     myAutoCorrect.Add(splitKeyValues(0), splitKeyValues(1))                  Else  &#39;break when we run out of lines                    Exit While                  End If        End While    End UsingEnd 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(&#39;,&#39;);                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&#39;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 (&amp;quot;using&amp;quot; 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&#39;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&#39;t support optional parameters, we explicitly declare a variable named &amp;quot;empty&amp;quot; to represent a
System.Reflection.Missing.Value type.  
Visual Basic  

Imports System.Collections.GenericImports Microsoft.Office.Interop.WordPublic Class WordWrapper    Public Sub AddToAutoCorrect(ByVal entries As Dictionary(Of String, String))        Dim oWord As Application = startWord()        Dim value As String        &#39;Loop through each entry from the dictionary        For Each key As String In entries.Keys        entries.TryGetValue(key, value) &#39;get the dictionary value        &#39;***Add the AutoCorrect entry into Word***        oWord.Application.AutoCorrect.Entries.Add(key, value)            Next        quitWord(oWord) &#39;cleanup    End Sub    Private Function startWord() As Application        &#39;Setup Word        Dim oWord As Application = New Application()        oWord.Visible = False        Return oWord    End Function    Private Sub quitWord(ByRef oWord As Application)        &#39;Quit Word        oWord.Application.Quit()    End SubEnd 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&amp;lt;string, string&amp;gt; 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&#39;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&#39;t delete any incorrect AutoCorrect entries. For example, we want to delete our &amp;quot;Hello,World&amp;quot;
 entry but don&#39;t want to fix &amp;quot;helo,hello,&amp;quot; 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    &#39;Loop through each entry from the dictionary    For Each key As String In entries.Keys        entries.TryGetValue(key, value) &#39;get the dictionary value        &#39;Loop through each Word AutoCorrect entry        For Each a As AutoCorrectEntry In oWord.AutoCorrect.Entries            &#39;Entries must match key and value            If a.Name = key And a.Value = value Then                a.Delete() &#39;Delete the AutoCorrect entry            End If        Next    Next    quitWord(oWord) &#39;cleanupEnd Sub





Visual C#  

public void RemoveFromAutoCorrect(Dictionary&amp;lt;string, string&amp;gt; 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 &amp;amp;&amp;amp; 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&#39;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 &amp;quot;horse&amp;quot; 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.&amp;nbsp; 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.
 
&amp;nbsp; 
</description>
	<link></link>
	<language>en</language>
	<pubDate>Thu, 23 May 2013 11:50:10 GMT</pubDate>
	<lastBuildDate>Thu, 23 May 2013 11:50:10 GMT</lastBuildDate>
	<generator>Rev9</generator>
	<item>
		<title>Re: When AutoCorrect Goes Bad</title>
		<description>
			<![CDATA[ <p>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..</p><p>posted by Illya Farhana</p>]]>
		</description>
		<link>http://channel9.msdn.com/coding4fun/articles/When-AutoCorrect-Goes-Bad#c633294000000000000</link>
		<pubDate>Wed, 31 Oct 2007 04:00:00 GMT</pubDate>
		<guid isPermaLink="true">http://channel9.msdn.com/coding4fun/articles/When-AutoCorrect-Goes-Bad#c633294000000000000</guid>
		<dc:creator>Illya Farhana</dc:creator>
	</item>
	<item>
		<title>Re: When AutoCorrect Goes Bad</title>
		<description>
			<![CDATA[ <p>Is there any way to implement the AutoCorrect functionality from Word into a Windows Form text box?</p><p>posted by Ryan Durkin</p>]]>
		</description>
		<link>http://channel9.msdn.com/coding4fun/articles/When-AutoCorrect-Goes-Bad#c633337236000000000</link>
		<pubDate>Thu, 20 Dec 2007 05:00:00 GMT</pubDate>
		<guid isPermaLink="true">http://channel9.msdn.com/coding4fun/articles/When-AutoCorrect-Goes-Bad#c633337236000000000</guid>
		<dc:creator>Ryan Durkin</dc:creator>
	</item>
	<item>
		<title>Re: When AutoCorrect Goes Bad</title>
		<description>
			<![CDATA[ <p>What would be the impact on removing autotext in winword.</p><p>posted by venugopal.madugula@gmail.com</p>]]>
		</description>
		<link>http://channel9.msdn.com/coding4fun/articles/When-AutoCorrect-Goes-Bad#c633530736000000000</link>
		<pubDate>Thu, 31 Jul 2008 04:00:00 GMT</pubDate>
		<guid isPermaLink="true">http://channel9.msdn.com/coding4fun/articles/When-AutoCorrect-Goes-Bad#c633530736000000000</guid>
		<dc:creator>venugopal.madugula@gmail.com</dc:creator>
	</item>
</channel>
</rss>