Brothers In Code

...a serious misallocation of .net resources

Keep a Winforms Application in the Foreground

I needed a way to force an application to stay on top.  I thought it would be as simple as "this.Activate" in the form's deactivate event.  It looked like it was trying to work - when clicking out of the app, it's start bar button would blink, but it wouldn't bring the app back on top.  I then proceeded to try just about everything under the sun:

  • Form.Activate
  • Form.BringToFront
  • Form.Focus
  • Form.Show
  • [DllImport("User32.dll")]
    public static extern Int32 SetForegroundWindow(int hWnd);

Everything seemed to do the same thing.  Finally I thought that maybe I was trying to refocus the form too soon.  I decided to create a timer and delay the Activate call:

//declare the timer
private System.Timers.Timer restoreFocusTimer = new System.Timers.Timer();

//setup the timer in the constructor
restoreFocusTimer.AutoReset = false;
restoreFocusTimer.SynchronizingObject = this;
restoreFocusTimer.Interval = 1000;
restoreFocusTimer.Elapsed += new System.Timers.ElapsedEventHandler(restoreFocusTimer_Elapsed);

//define the handler
void restoreFocusTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
  this.Activate();
}


//enable the timer in the deactivate event (I also added a preprocessor directive so i could disable it when debugging.
private void MainForm_Deactivate(object sender, EventArgs e)
{
  if (!this.formClosing)
  {
    #if !NOALWAYSONTOP
    restoreFocusTimer.Enabled = true;
    #endif
   }
}

 

Loading