title: Sendkey to background program
body: <p>I'm trying to create an application that will send a keystroke to an application (by process or window) in the background at a set interval(ms). I've found a few different answers on this topic but I need an ELI5 (explain like I'm 5) answer. As a test I used the following code I found to send keys to notepad.</p>
  
  <pre><code>using System;
  using System.Diagnostics;
  using System.Runtime.InteropServices;
  using System.Windows.Forms;
  
  namespace TextSendKeys
  {
      class Program
      {
          [DllImport("user32.dll")]
          static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
  
          static void Main(string[] args)
          {
              Process notepad = new Process();
              notepad.StartInfo.FileName = @"C:\Windows\Notepad.exe";
              notepad.Start();
  
              // Need to wait for notepad to start
              notepad.WaitForInputIdle();
  
              IntPtr p = notepad.MainWindowHandle;
              ShowWindow(p, 1);
              SendKeys.SendWait("ABC");
          }
      }
  }
  </code></pre>
  
  <p>This code allows me to send the keystrokes to notepad. It opens notepad, but can't do it in the background.</p>
  
  <p><strong>Answer</strong></p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Collections;
  using System.ComponentModel;
  using System.Data;
  using System.Diagnostics;
  using System.Threading;
  using System.Drawing;
  using System.Runtime.InteropServices;
  using System.Windows.Forms;
  
  
  namespace TextSendKeys
  {
      class Program
      {
  
          [DllImport("user32.dll")]
          [return: MarshalAs(UnmanagedType.Bool)]
          static extern bool SetForegroundWindow(IntPtr hWnd);
  
      static void Main(string[] args)
      {
          Process[] processes = Process.GetProcessesByName("process name here");
          Process game1 = processes[0];
  
          IntPtr p = game1.MainWindowHandle;
  
          SetForegroundWindow(p);
          SendKeys.SendWait("{1}");
          Thread.Sleep(1000);
          SendKeys.SendWait("{1}");
  
          }
      }
  }
  </code></pre>