将KeyBoardKeys发送到同一项目上启动的另一个应用程序

本文关键字:启动 另一个 应用程序 项目 KeyBoardKeys | 更新日期: 2023-09-27 18:24:13

我正试图发送一些键盘键来控制在同一项目上推出的game boy高级模拟器,但它找不到进程

 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.");
        }
    }

我不知道我是不是把钥匙寄错了。谢谢你们!

将KeyBoardKeys发送到同一项目上启动的另一个应用程序

您的密钥不太可能被发送到正确的进程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)。