Share via


Overriding Built-in Commands

Under certain circumstances an application might find it useful to override a built-in speech recognizer command. The Send() method on the SendKeys class can be used to send keystrokes to an active application.

Example

When the Windows desktop speech recognizer is in listening mode, its built-in grammar enables the recognizer to recognize voice commands to start and control a number of applications. For example, a user can start Notepad by saying "start Notepad."

The following example creates a simple speech recognition grammar that recognizes the command "start Notepad." It also sets the new grammar’s Priority to its highest possible value, 127. Given that both the recognizer’s dictation grammar and the speech recognition grammar of this example contain the phrase "start Notepad," the grammar with the higher Priority will be the one that is used to match this command. As a result, the speech recognition grammar of this example circumvents the speech recognizer’s dictation grammar for this command. When a user says "start Notepad," the recognition grammar of this example echoes this string to the speech recognizer’s user interface without causing Notepad to be started.

namespace WindowsFormsApplication1

  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
      sr = new SpeechRecognizer();
      sr.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(sr_SpeechRecognized);

      GrammarBuilder gb = new GrammarBuilder();
      gb.Append("Start Notepad");

      Grammar g = new Grammar(gb);
      g.Priority = 127;

      sr.LoadGrammar(g);
    }

    void sr_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
    {
      SendKeys.Send("Start Notepad");
    }

    SpeechRecognizer sr;
  }
}