IOIOI
IOIOI

Reputation: 9

How to execute code as soon as the form loads?

I'm a student and haven't coded for long at all and as such don't know many of the features that are usable.

Right now I'm facing an issue where I have my first form summon another form that I then want to rapidly change colors as soon as it opens.

I had already made a form that rapidly changes color as soon as I press a button but here I want it to start as soon as it appears.

I understand that this question might have been asked before but I couldn't really find an answer that worked. Some people were saying stuff about using "OnLoad" or "Application.run" but I can't seem to get those things to come up when I type them into Microsoft visual studio.

Here is the code of the initial form:

    private void btnkör_Click(object sender, EventArgs e)
    {
        Form2 f2 = new Form2();
        f2.Show();
    }

And here is the code of the second form that is summoned by the first:

  private void Form2_Load(object sender, EventArgs e)
    {
        this.Visible = true;

        Timer.Enabled = true;
    }

    private void Timer_Tick(object sender, EventArgs e)
    {         
        Random Generator = new Random();

        BackColor = Color.FromArgb(255, Generator.Next(1, 256), Generator.Next(1, 256), Generator.Next(1, 256));
    }

FYI the second form is a completely empty square form while the first is a very small window taken up entirely by the "kör" button (means "run" in Swedish)

Upvotes: 0

Views: 109

Answers (1)

Nesaje
Nesaje

Reputation: 595

Why would you need a timer? Is it important that user notices such color change? Otherwise, why would you not just set that color before showing the form? No timers involved, event handlers etc. With this approach, you're in full control.

private void btnkör_Click(object sender, EventArgs e)
{
    Form2 f2 = new Form2();
    f2.BackColor = Color.OrangeRed;
    f2.Show();
}

This way, your back color will be set, after form is created/initialized and before it is shown. It will be displayed as 'OrangeRed' and user will not notice such change.

Of course, put your code in place that randomly generates color. Bear in mind second comment related to the 'Random' object.

In case you do not need random color, but some static, you could set BackColor property directly on the form (in design mode) and would not need this piece of code.

Upvotes: 1

Related Questions