Search code examples
c#windowsdesktop-applicationbuttonclickmouseclick-event

How to handle button click event in program.cs in C#


I have two forms i.e. Form A and Form B. If Button X of Form A is clicked only then Form B will show and Form A will hide. I have to do all this in program.cs of a windows Form Application.

Here is the code snipped

            FormA A = new FormA ();
            FormB B = new FormB ();

            A.Show();                    
            if(Button in form A is clicked then )
                  B.Show() and A.hide();
            else 
                  application.close()

Solution

  • First thing required is to have the button visible outside the form class.
    This is done setting the Modifier property in the WinForms Designer to public, or, if you create the button programmatically, you need to declare the variable public at the form level.

    Now, with the button public you could write an event handler for its click event and write that handler inside the Program.cs class.
    This also requires that your FormA and FormB variables are usable inside the event handler of the button, so you need to have also them public.

    public static class Program
    {
        static FormA A;
        static FormB B;
    
        public static void Main()
        { 
    
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
    
            A = new FormA();
            B = new FormB();
            A.Button1.Click += onClick;    
    
            // This should show the A instance
            Application.Run(A);
            ....
        }
        public static void onClick(oject sender, EventArgs)
        {
            A.Hide();
            B.Show();
        }
    }