The problem is that the active window does not change, and pointer GetForegroundWindow changes the value. Ie in my case, when you click on a notebook, the form disappears and appears at the same second.

[DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); void FindF2B(){ var hWndParent = FindWindow("Notepad", "Untitled - Notepad"); if(GetForegroundWindow() == hWndParent){ if(this.InvokeRequired){ this.Invoke(new MethodInvoker(delegate{ this.Hide();})); } }else{ if(this.InvokeRequired){ this.Invoke(new MethodInvoker(delegate{ this.Show();})); } } 
  • one
    You do wrong Show. Making Show ForegroundWindow becomes your window. Read carefully the SetWindowPos function (with SWP_NOACTIVATE SWP_NOZORDER SWP_SHOWWINDOW flags) should help - nick_n_a
  • one
    Also, your window will appear, and if it is activated, it will hide (according to your rule). In addition to hWndParent, you all the way to the "filter" you also need your window. - nick_n_a

1 answer 1

  void FindF2B(){ var hWndParent = FindWindow("Notepad", "Untitled - Notepad"); var myFormWindow = FindWindow(null, "Location"); if(GetForegroundWindow() == hWndParent && GetForegroundWindow() != IntPtr.Zero){ ShowWindow(myFormWindow , 1); }else{ ShowWindow(myFormWindow , 0); } [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);