title: C# global keys and SetForegroundWindow
body: <p>I'm using a C# app to listen for a global combination of keys (ctrl+F9) that will bring a specific window to front.</p>
  
  <p>This is the code I'm using to bring a window to front, it works only if fired by a Button event:</p>
  
  <pre><code>    private void button3_Click(object sender, EventArgs e)
      {
          SetForegroundWindow(ptrActiveWindow.ToInt32());
          ShowWindowAsync(ptrActiveWindow, SW_RESTORE);
      }
  </code></pre>
  
  <p>For hooking, I've used a class taken from <a href="http://www.codeproject.com/KB/cs/CSLLKeyboardHook.aspx" rel="nofollow">http://www.codeproject.com/KB/cs/CSLLKeyboardHook.aspx</a>, which is fully listed here: </p>
  
  <p><a href="http://code.google.com/p/code-commenter/source/browse/trunk/key+preview/globalKeyboardHook.cs?spec=svn3&amp;r=3" rel="nofollow">http://code.google.com/p/code-commenter/source/browse/trunk/key+preview/globalKeyboardHook.cs?spec=svn3&amp;r=3</a></p>
  
  <p>Whenever I have a F9 KeyUp event after a CTRL KeyDown and before a CTRL KeyUp (CTRL is still pressed), I call my method: </p>
  
  <pre><code>    private void restore(IntPtr hWnd)
      {
  
        IntPtr ptrCurrentActiveWindow = GetForegroundWindow(); //comment line
        ShowWindowAsync(ptrCurrentActiveWindow, SW_MINIMIZE); //comment line
  
          ShowWindowAsync(hWnd, SW_RESTORE);
          SetFocus(hWnd);
          SetForegroundWindow(hWnd.ToInt32());
  
      }
  </code></pre>
  
  <p>This does nothing. My window is activated in the background (I can see it blinking in the taskbar), but does not get restored. </p>
  
  <p>The only way I can move around this is to use the commented code: minimize the currently active window and afterwards restore the window I want to see.</p>
  
  <p>All help is appreciated, 
  Thanks.</p>
  
  <p>Global hotkey, working version:</p>
  
  <pre><code>    private void Form1_Load(object sender, EventArgs e)
      {
          string atomName = Thread.CurrentThread.ManagedThreadId.ToString("X8") + this.GetType().FullName;
          short HotkeyID = GlobalAddAtom(atomName);
          if (!RegisterHotKey(this.Handle, HotkeyID, (uint)GlobalHotkeys.MOD_CONTROL, (uint)Keys.D5))
              listBox.Items.Add("failed: " + "unable to register hotkey. Error: " + Marshal.GetLastWin32Error().ToString());
          else
              listBox.Items.Add("succeeded adding hotkey id"+(uint)Keys.D5);
      }
  
      protected override void WndProc(ref Message m)
      {
          const int WM_HOTKEY = 0x0312;
  
          if (m.Msg == WM_HOTKEY)
          {
              if ((short)m.WParam==HotkeyID)
                  listBox.Items.Add("Hotkey."+ (short)m.WParam);
          }
          base.WndProc(ref m);
      }
  </code></pre>