I am trying to send some keyboard keys to control a game boy advance emulator launched on the same project, but it doesnt find the process
public partial class MainWindow : Window
{
[DllImport("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);
///////////////////////
/// <summary>
/// Method used to run VisualBoyAdvance emulator with a GBA ROM
/// </summary>
/// <param name="command"></param>
public void RunProgram()
{
// PATH of the ROM
const string ex1 = @"C:\GameBoy\marioKart.gba";
// Use ProcessStartInfo class
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
//Name of the emulator, PATH
startInfo.FileName = @"C:\GameBoy\VisualBoyAdvance-SDL.exe";
//Can be set to hidden to hide.
startInfo.WindowStyle = ProcessWindowStyle.Normal;
//Arguments if needed
startInfo.Arguments =" " + ex1;
try
{
// Start the process with the info we specified.
// Call WaitForExit and then the using statement will close.
using (Process execProcess = Process.Start(startInfo))
{
//Select the process to send the keys
Process[] localAll = Process.GetProcesses();
Process p = localAll[0];
Console.WriteLine(p);
if( p != null)
{
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
//Sending some "Enter" keys
SendKeys.SendWait("~");
SendKeys.SendWait("~");
SendKeys.SendWait("~");
SendKeys.SendWait("{ENTER}");
}
execProcess.WaitForExit();
}
}
catch
{
Console.Write("~");
Console.Write("Error.");
}
}
I dont know if I am not sending the keys right or whatever. Thank you guys!
It is unklikely that your keys are being sent to the correct process localAll[0]
. Make sure you are sending them to the right application (e.g. Process[] processes = Process.GetProcesses().Where(p => p.ProcessName == "VisualBoyAdvance-SDL")
or Process p = Process.GetProcessesByName("VisualBoyAdvance-SDL")
. Make sure check for a 0 length array in the first case or null in the second.
Other than that, using SendKeys.SendWait should work for you as this is essentially the Win32 API SendMessage (SendKeys.Send would use the Win32 API PostMessage).