2015-11-24 27 views
2

我想送一些鍵盤按鍵來控制在同一項目上推出了遊戲男孩前進模擬器推出的又一aplication,但它不查找進程發送KeyBoardKeys在同一個項目

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

    } 

我不知道如果我沒有正確地發送密鑰或其他。感謝你們!

+0

在過程完成打開之前密鑰是否可能發送得太快?也許你想介紹一個小的在進程打開和發送密鑰之間的延遲 – Ruslan

+0

我剛剛試過這個,它不工作:System.Threading.Thread.Sleep(5000) – user5034027

+0

而不是使用'Thread.Sleep',嘗試'p.WaitForInputIdle ()',把它放在前面'IntPtr h = p.MainWindowHandle'。 – Ruslan

回答

0

您的密鑰不可能被髮送到正確的過程localAll[0]。請確保您將它們發送到正確的應用程序(如Process[] processes = Process.GetProcesses().Where(p => p.ProcessName == "VisualBoyAdvance-SDL")Process p = Process.GetProcessesByName("VisualBoyAdvance-SDL")。請確保您在第一種情況下長度爲0陣列或空在第二位。

除此之外,使用SendKeys.SendWait應該爲你工作因爲這本質上是Win32 API SendMessage(SendKeys.Send將使用Win32 API PostMessage)

+0

另請參閱MSDN中的[following](https://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.send(v = vs.110).aspx):SendKeys類具有已針對.NET Framework 3.0進行了更新,以使其可用於在Windows Vista上運行的應用程序。 Windows Vista增強的安全性(稱爲用戶帳戶控制或UAC)可防止以前的實現按預期工作...... –