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 determine when a control or component has been selected in the designer surface?

You can subscribe to the SelectionChanged event in your control designer.

using System.ComponentModel.Design;


public class CustomContainerDesigner : ParentControlDesigner 
{ 
  private bool iamSelected;

  public override void Initialize( IComponent component ) 
  { 
    base.Initialize( component ); 
    selectionService = (ISelectionService) GetService( typeof( ISelectionService ) ); 
    if ( selectionService != null ) 
      selectionService.SelectionChanged +=
        new EventHandler( OnSelectionChanged ); 
  }

  private void OnSelectionChanged( object sender, EventArgs e ) 
  { 
    // To find out the current selection (can be more than one) do this: 
    iamSelected = false; 
    ISelectionService selectionService =
      (ISelectionService) GetService( typeof( ISelectionService ) ); 
    if ( selectionService != null ) 
    { 
      foreach ( object selectedComponent in 
          selectionService.GetSelectedComponents() ) 
        if ( selectedComponent == Component ) 
        {
          iamSelected = true;
          break;
        }
    } 
  } 
}

Contributed from George Shepherd's Windows Forms FAQ