c# - 将键盘键发送到在同一项目上启动的另一个应用程序

标签 c# sendkeys

我正在尝试发送一些键盘键来控制在同一项目上启动的 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/

相关文章:

c# - 开放通用类型是否被认为是具体的?我们如何通过参数化来限定抽象?

c# - 如何避免 'SamlAssertion.NotOnOrAfter condition is not satisfied'错误

c# - 在文本框中按回车键执行按钮命令

c++ - 我如何将击键发送到一个程序?

android - 当测试按下开始按钮时游戏没有开始

c# - 如何将左右系统键发送到 SendKeys.Send()?

c# - 避免调试器因线程中捕获的异常而停止

c# - 在 .Net MVC C# Web 应用程序中从用户本地计算机选择文件?

c# - C#中SendKeys的跨平台实现?