Home > Blockchain >  Where is the call of the button_click method in C# in Visual Studio 2019?
Where is the call of the button_click method in C# in Visual Studio 2019?

Time:09-30

(Newby on Visual Studio 2019 and C#, familiar with OOP in Java)

Visual Studio 2019 icw .NET windows dev. Coding in C#.

When I add an button to a form and doubleclik on it, the method-definition gets created in Form1.cs and looks like:

private void button1_Click(object sender, EventArgs e)
{

}

But where does this method get called? I've looked in the button class, control class and form1 class but can't find it.

Thanks in advance.

CodePudding user response:

The method (button1_Click) is wrapped into an EventHandler and added as subscriber of the Click event of the form object container.

this.button1.Click  = new System.EventHandler(this.button1_Click);

The above code is generated by the designer in a different file groupped by VS together with our source file.

In fact your form is a C# partial class. The rest of the class is defined in the file .Designer.cs (for instance Form1.Designer.cs).

So your method will be called as soon as button will be clicked.

CodePudding user response:

But where does this method get called?

The WinForms framework calls it, because it's assigned as a handler to an Event.

This is hooked up in the form's Designer file, which is auto-generated by Visual Studio. It's named {FormName}.Designer.cs.

enter image description here

Inside that file is a Region called "Windows Form Designer generated code", which when you made modifications to the form with the visual designer will update accordingly. This is actually where your method is being registered as an event handler.

For example, in my simple calculator app, the "8" button is being assigned to a method named ButtonClick when clicked.

// 
// btn8
// 
this.btn8.Location = new System.Drawing.Point(58, 46);
this.btn8.Name = "btn8";
this.btn8.Size = new System.Drawing.Size(40, 36);
this.btn8.TabIndex = 2;
this.btn8.Text = "8";
this.btn8.UseVisualStyleBackColor = true;
this.btn8.Click  = new System.EventHandler(this.ButtonClick);

You can also view and modify the assigned events from the Events tab in the Properties paine in the Form Designer, when the correct control is selected.

enter image description here

CodePudding user response:

It is an Async function, which get called when the user click the button, for this the function get linked to the object "button1" by an EventHandler in a file you can access by right clicking the UI file on the right of visual studio.

more info here: https://docs.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-add-an-event-handler?view=netdesktop-5.0

welcome to the C# world :)

  • Related