views:

156

answers:

3

I am writing a Windows Forms Application in C#. I need to be able to bring it to the foreground. After some Googling and experimentation, I have a working solution that looks pretty hacky.

I would like to know the elegant way to do this, if there is one. I need the app to restore and come to the foreground whether it was minimized, or not minimized but in background.

Current code looks like this:

WindowState = FormWindowState.Minimized;
WindowState = FormWindowState.Normal;
BringToFront();
Focus();
A: 

Have you tried Form.Activate?

This code seems to do what you want, by restoring the form to normal size if minimized and then activating it to set the focus:

if (this.WindowState == FormWindowState.Minimized)
{
    this.WindowState = FormWindowState.Normal;
}

this.Activate();

Warning: this is annoying! If it's just an app for your personal use, as you say, maybe you can live with it. :)

bobbymcr
Yes, that doesn't work at all.
RedFilter
Revised code works perfectly.
RedFilter
I just tried this. Activate() will not work if the form is an MDI child form and the user is working with another application.
Jacob Seleznev
+1  A: 

You can set .TopMost to true, call DoEvents(), and then set .TopMost back to false. It's still hackish, but if Activate and Show aren't working it's better than minimizing/re-showing.

Joel Coehoorn
This does not work for me, at least not in the Visual Studio host debug environment.
RedFilter
+3  A: 
     private static class User32
 {
  [DllImport("User32.dll")]
  internal static extern IntPtr SetForegroundWindow(IntPtr hWnd);

  [DllImport("user32.dll")]
  internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

  internal static readonly IntPtr InvalidHandleValue = IntPtr.Zero;
  internal const int SW_MAXIMIZE = 3;
 }
 public void Activate()
 {
  Process currentProcess = Process.GetCurrentProcess();
  IntPtr hWnd = currentProcess.MainWindowHandle;
  if (hWnd != User32.InvalidHandleValue)
  {
   User32.SetForegroundWindow(hWnd);
   User32.ShowWindow(hWnd, User32.SW_MAXIMIZE);
  }
 }
Jacob Seleznev
Hmm, that doesn't win any prizes for elegant, is there not a good native .Net way?
RedFilter
It DOES work though.
RedFilter
From MSDN:"The SetForegroundWindow function puts the thread that created the specified window into the foreground and activates the window".With this your application can force the window to the foreground, while the user working with another application.
Jacob Seleznev