Useful C# Tricks
C# includes a string method that I've missed in C++ for ages, the Replace method, which lets your program do simple text replacements in single lines of code. For example, for your computer to respond by speaking the time of day, include "%time%" in the response string ("The time is now %time%"). Now add a line:
sResponse = sResponse.Replace(
"%time%",DateTime.Now.ToString("h m"));
which gets the time of day from the system, formats it as a string, and replaces it in the sReponse string. The example program includes similar functionality for the user's name, date, day of week, and so on.
It is useful to be able to direct a browser with voice commands. Windows includes a ShellExecute function that does the trick by opening any file with its appropriately registered application. So if you give it a file name with an http:// prefix, it will open a browser to open the file. Since ShellExecute is not part of the C# library, you will need to declare it explicitly like this:
[DllImport("Shell32.dll")]
public static extern int ShellExecuteA(
int hwnd,
string lpOperation,
string lpFile,
string lpParameters,
string lpDirectory,
int nShowCmd);
before you call it like this:
int ProcID = ShellExecuteA(
0,"open",sFileName,null,"",1);
A returned ProcID of less than 32 indicates an error. You can also save the ProcID and pass it to other system functions to close the program (for example).
Scraping Data From Web Sites
One of the common uses for speech-enabled programs is information presentation you ask your computer a question and it speaks the answer. Many of the answers are on web pages in relatively predictable locations, and C# provides all the tools to retrieve web-page information and present it verbally. Because web pages are copyrighted, I would suggest getting permission from the web site owner before distributing a program that performs this type of function.
WebRequest myRequest =
WebRequest.Create(sURL);
WebResponse myResponse =
myRequest.GetResponse();
Stream myStream =
myResponse.GetResponseStream();
string sHtml="";
System.Text.Encoding encode =
System.Text.Encoding.GetEncoding("utf-8");
StreamReader readStream =
new StreamReader( myStream, encode );
Char[] read = new Char[256];
int count =
readStream.Read( read, 0, 256 );
while (count > 0)
{
string str =
new string(read, 0, count);
sHtml += str;
count =
readStream.Read(read, 0, 256);
}
myStream.Close();
With this code, you end up with the string sHttpResponse containing the HTML for the page at sURL. Now you can parse the string to find the information you'd like to speak.