我正在尝试发送一些键盘键来控制在同一项目上启动的 game boy advance 模拟器,但它找不到进程
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.");
}
}
我不知道我是否没有正确发送 key 或其他什么。谢谢大家!
最佳答案
您的 key 不太可能被发送到正确的进程 localAll[0]
。确保将它们发送到正确的应用程序(例如 Process[] processes = Process.GetProcesses().Where(p => p.ProcessName == "VisualBoyAdvance-SDL")
或 Process p = Process.GetProcessesByName("VisualBoyAdvance-SDL")
。确保在第一种情况下检查长度为 0 的数组,在第二种情况下检查是否为 null。
除此之外,使用 SendKeys.SendWait 应该对您有用,因为这本质上是 Win32 API SendMessage(SendKeys.Send 将使用 Win32 API PostMessage)。
关于c# - 将键盘键发送到在同一项目上启动的另一个应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33898237/