Lukas

Lukas

  • NA
  • 2
  • 1.9k

Sending a Key to another program

Aug 4 2014 2:10 PM
Hey,
I'm new here so I'm sorry if something is wrong with my post! :)
I'm learning C# since last year so I'm not really skilled, but today I started working on a speech recognition for the game "Elite Dangerous" because Voice Attack costs money. With the help of google I am really close and the speech recognition works fine so far. I can say something and if it is a special word a key will be pressed. With that I can "write" in a lot of applications such as notepad, calculator, the Elite Dangerous Launcher and so on. But if I try to send keys to the game itself it does not work. I read a lot about this problem, but I didn't find any helpful solution. Actually I try to find the window and set it to the foreground:
[Code] 
public void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
if (!RecognizerState)
return;
this.Invoke((MethodInvoker)delegate
{
richTextBox1.Text += (" " + "\n" + e.Result.Text.ToLower());

if (e.Result.Text.ToLower() == "lights on")
{

IntPtr calculatorHandle = FindWindow(null, "EliteDangerous");
SetForegroundWindow(calculatorHandle);
SendKeys.Send("{l}");

}
});


on the top of Form1 I added:


[DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName,
string lpWindowName);
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[/Code]


I thankful for every answer! :)
By the way, is there a better way to show my code here?