Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to click a button on form load using C#

How do i click a button on foam load using C#? My button is called: btnFacebookLogin

I have tried this following:

private void Form1_Shown(Object sender, EventArgs e) 
{
   btnFacebookLogin.PerformClick(); 
}

I am using WinForms C# .NET 4

like image 355
PriceCheaperton Avatar asked Dec 20 '22 19:12

PriceCheaperton


2 Answers

Be sure to link your handler after InitializeComponent() and to Load event

public Form1()
{
   InitializeComponent();
   Load += Form1_Shown;
}

private void Form1_Shown(Object sender, EventArgs e) 
{
   btnFacebookLogin.PerformClick(); 
}
like image 96
Justin Iurman Avatar answered Jan 02 '23 10:01

Justin Iurman


Is there a specific reason you need to actually click the button?

I would just move the code in the click event into a function, then call that function from both the load event and the click event. It will get around the need to call click()

For instance:

private void Form1_Shown(Object sender, EventArgs e) 
{
   DoFacebookLogin();
}

private void btnFacebookLogin_Click(Object sender, EventArgs e)
{
    DoFacebookLogin();
}

private void DoFacebookLogin()
{
    //Do Work here
}
like image 32
Obsidian Phoenix Avatar answered Jan 02 '23 10:01

Obsidian Phoenix