Search code examples
c#controlscomposite-controls

How to detect C# control name changed?


I created a composite control using C# Windows Forms Control Library, when I use the new control in a test program, I want to find a way to detect when did the name of new control changed at design time, what should I do?


Solution

  • You can use the IComponentChangeService (in System.ComponentModel.Design) like in this example:

    public class MyControl : UserControl
    {
        public event EventHandler NameChanged;
        protected virtual void OnNameChanged()
        {
            EventHandler handler = NameChanged;
            if (handler != null) handler(this, EventArgs.Empty);
        }
    
        protected override void OnCreateControl()
        {
            base.OnCreateControl();
    
            IComponentChangeService changeService = (IComponentChangeService)GetService(typeof(IComponentChangeService));
            if (changeService == null) return; // not provided at runtime, only design mode
    
            changeService.ComponentChanged -= OnComponentChanged; // to avoid multiple subscriptions
            changeService.ComponentChanged += OnComponentChanged;
        }
    
        private void OnComponentChanged(object sender, ComponentChangedEventArgs e)
        {
            if (e.Component == this && e.Member.Name == "Name")
                OnNameChanged();            
        }
    }
    

    This service is only provided in design mode, not at runtime.
    I unsubscribe and subscribe again to the ComponentChanged event (to avoid multiple subscriptions).

    In the event handler OnComponentChanged I check if my name has changed and raise the NameChanged event.