title: Get key pressed from other application C#
body: <p>I would like to get the key pressed by user on other application. For example, in notepad, not the program itself. Here is my coding that using <code>PostMessage</code> method to continuously send key to notepad but however, I wish to stop it when some key is pressed.</p>
  
  <pre><code>using System.Diagnostics;
  using System.Runtime.InteropServices;
  using System.Threading;
  
         [DllImport("user32.dll")]
  public static extern IntPtr FindWindow(
      string ClassName,
      string WindowName);
  
  [DllImport("User32.dll")]
  public static extern IntPtr FindWindowEx(
      IntPtr Parent,
      IntPtr Child,
      string lpszClass,
      string lpszWindows);
  
  [DllImport("User32.dll")]
  public static extern Int32 PostMessage(
      IntPtr hWnd,
      int Msg,
      int wParam,
      int lParam);
  
  private const int WM_KEYDOWN = 0x100;
  
  public Form1()
  {
      InitializeComponent();
  }
  
  private void button1_Click(object sender, EventArgs e)
  {
      Thread t = new Thread(new ThreadStart(Test));
      t.Start();
  }
  
  Boolean ControlKeyDown = true;
  
  public void Test()
  {
      // retrieve Notepad main window handle
      IntPtr Notepad = FindWindow("Notepad", "Untitled - Notepad");
  
      if (!Notepad.Equals(IntPtr.Zero))
      {
          // retrieve Edit window handle of Notepad
          IntPtr Checking = FindWindowEx(Notepad, IntPtr.Zero, "Edit", null);
  
          if (!Checking.Equals(IntPtr.Zero))
          {
  
              while (ControlKeyDown)
              {                        
                  Thread.Sleep(100);
  
                  PostMessage(Checking, WM_KEYDOWN, (int)Keys.A, 0);                                                             
              }
          }
      }
  }
  </code></pre>
  
  <p>Hence, my idea is set the <code>ControlKeyDown</code> to <code>false</code> when user pressed <code>X</code> key in notepad. After research through internet, I found out this code and edited:</p>
  
  <pre><code>protected override void OnKeyDown(KeyEventArgs kea)
  {
      if (kea.KeyCode == Keys.X)
      ControlKeyDown = false;
  }
  </code></pre>
  
  <p>Yes, by this, it definitely will stop the looping but this is not I want as it will stop the loop when user presses <code>X</code> key on the program but not in notepad. This is because the <code>KeyEventArgs</code> is <code>System.Windows.Forms.KeyEventArgs</code> and not Notepad.</p>
  
  <p>Need help :(</p>