AutoText is a powerful utility when typing lot of letters, e-mails or any other text. In a recent blog entry, I described how to solve this using the SpellCheckText event of TX Text Control. If you are using TX Spell .NET in combination with TX Text Control, the SpellCheckText event is blocked to avoid a potential interplay of two event listeners which might cause infinite loops.

You can easily replace the SpellCheckText event with the Changed event in order to replace keywords. The following code shows how to do that:

Hashtable htAutoCorrect;

// create a new hash table for the replacements
htAutoCorrect = new Hashtable();
htAutoCorrect["vbb"] = "Visual Basic";
htAutoCorrect["css"] = "CSharp";

private void textControl1_Changed(object sender, EventArgs e)
{
    // check the MisspelledWord collection for entries in the
    // hash table. Replace the word immediately.
    // Shortcut (key in hash table) must be unique and
    // "misspelled" for the spell checker
    foreach (MisspelledWord word in textControl1.MisspelledWords)
    {
        if (htAutoCorrect.ContainsKey(word.Text))
        {
            int iStart =
                ((string)htAutoCorrect[word.Text]).Length - word.Length;

            textControl1.MisspelledWords.Remove(word,
                htAutoCorrect[word.Text].ToString());
            textControl1.Selection.Start += iStart;

            break;
        }
    }
}

Implementing AutoCorrect Using TX Spell .NET's Suggestions

While the above method uses a custom hash table to replace keywords with it's fixed values, you might want to replace misspelled words automatically on a specific action such as pressing {CTRL}+{SPACE}. The following code shows how to trap the keystrokes, get the misspelled word at the current text position and how to replace this misspelled word with the first suggestion from TX Spell .NET:

bool bActionKeys = false;

private void textControl1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Control && e.KeyCode == Keys.Space)
    {
        bActionKeys = true;
    }
}

private void textControl1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (bActionKeys == true)
    {
        e.Handled = true;
        bActionKeys = false;

        MisspelledWord word = textControl1.MisspelledWords.GetItem(
            textControl1.InputPosition.TextPosition);

        txSpellChecker1.CreateSuggestions(word.Text);

        if (txSpellChecker1.Suggestions.Count == 0)
            return;

        int iStart = txSpellChecker1.Suggestions[0].Text.Length - word.Length;

        textControl1.MisspelledWords.Remove(
            word, txSpellChecker1.Suggestions[0].Text);

        if(iStart > 0)
            textControl1.Selection.Start += iStart;
        else
            textControl1.Selection.Start -= iStart;
    }
}