C# – How to execute a method after usercontrol is fully visible

cnetwinforms

I have a usercontrol containing a textbox which i load dynamically onto a form.
At the form's start up i initiate the usercontrol and set it's visibility tag to 'false'.
I want to trigger a method automatically when the usercontrol becomes visible, since this method writes some output to the textbox this method should only start executing after the usercontrol and all it's inherited controls become visible to the user.

I thought the paintEventHandler should be the last event that gets triggered when a form and its inherited controls gets repainted after eg a control's visibility gets changed.

So subscribing to the paintEventHandler should trigger my subscribed method after the form is fully repainted, but apparently is does not, my method executes while my textbox is still hidden, turning only visible after the method finished executing.

Any thoughts on this?

private void processControl_SetActive(object sender, CancelEventArgs e)
        {

            this.BeginInvoke((MethodInvoker)delegate
           {
               this.Paint += new PaintEventHandler(processControl_Paint);
           });

        }

void processControl_Paint(object sender, PaintEventArgs e)
        {
            //Should only be called when everything is fully loaded and visible on the form.
            //Application.DoEvents()  ->probably bad idea??
            AddStuffToTextBox();
        }

Best Answer

You could try adding the text box initialization code to a handler for the Enter event of the user control, which fires when the control gains input focus and then in your code that activates the control make sure you call the Focus method on the control to set it active. You would probably want to keep a flag so this was done only on the first occurrence of the control gaining input focus.