Hi,
I am writing a small console application in which I instantiate a new
object and add an event listener to it. My goal is now to wait and sit
there until such an event occurs, in which case my listener gets called.
My problem is: how do I implement that? Clearly, if I just add my
listener to the object, my program will terminate after that. It seems
that adding an infinite loop after that doesn't work (blocking?), so I
was thinking of using threads. My initial attempt didn't prove
successful, though.
Anybody knows how to do this? It's a very unambitious goal and I am
sure there must be a way. By the way, it's about Microsoft Speech API
(SAPI) and the event listener here is the callback function that is
called whenever sth was recognized.
Here is the code skeleton:
class Program {
// Declaration for variables
...
public void init()
{
//Initialize object
objRecoContext = new SpeechLib.SpSharedRecoContext();
...
// Add listener
objRecoContext.Recognition += new
_ISpeechRecoContextEvents_RecognitionEventHandler(handleRecognition);
}
public void handleRecognition(...)
{
System.console.WriteLine("Got it");
}
public static void Main()
{
Program p = new Program();
p.init();
}
}
I would be really glad for any help.
Thanks!
Loading
Sunny ChenPosted Sep 8, 2008, 4:33 AM
Add "Console.ReadLine()" as the last statement in Main();
AlanPosted Sep 6, 2008, 7:41 PM
I suspect your problem here is that SAPI events can only be handled in a thread which has a message pump i.e. a windows forms application. In fact, I can't find any examples of .NET SAPI applications on the web which are not windows forms based.
However, you might still be able to start a message pump on your main thread without the need to create a form by using the parameterless overload of the Application.Run() method. You would then need to call Application.Exit() or Environment.Exit(1) to stop the application.
To try this, you'll need to add a reference to System.Windows.Forms.dll to your Console application and also add this 'using' directive:
using System.Windows.Forms;
Then just change your init() method to the following:
public void init()
{
//Initialize object
objRecoContext = new SpeechLib.SpSharedRecoContext();
...
// Add listener
objRecoContext.Recognition += new
_ISpeechRecoContextEvents_RecognitionEventHandler(handleRecognition);
// start message pump
Application.Run();
}
and add Application.Exit() wherever you need to stop the application.