Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I show a form without making it active?

Normally when you make a Form visible by setting the Visible property to true, it will show the form and set the focus too. In some cases however, you do not want it to take focus until the user clicks on it. To get this behavior, do the following utility code:

When you want to show a form without activating it:

UtilFuncs.SetVisibleNoActivate( myForm, true ); // true to show. 

When you want to hide it:

UtilFuncs.SetVisibleNoActivate( myForm, false ); // false to hide. 

public class UtilFuncs 
{ 
  [ DllImport( "user32.dll" ) ] 
  extern public static bool SetWindowPos( IntPtr hWnd, 
    IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags );
 
  public const int HWND_TOPMOST = -1; // 0xffff 
  public const int SWP_NOSIZE = 1; // 0x0001 
  public const int SWP_NOMOVE = 2; // 0x0002 
  public const int SWP_NOACTIVATE = 16; // 0x0010 
  public const int SWP_SHOWWINDOW = 64; // 0x0040 
  
  public static void ShowWindowTopMost( IntPtr handle ) 
  { 
    SetWindowPos( handle, (IntPtr) HWND_TOPMOST, 0, 0, 0, 0, 
      SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE | SWP_SHOWWINDOW ); 
  }
 
  public static void SetVisibleNoActivate( Control control, bool visible ) 
  { 
    if ( visible ) 
      ShowWindowTopMost( control.Handle ); 
    control.Visible = visible; 
  } 
}

Contributed from George Shepherd's Windows Forms FAQ



Page view counter