Excavator
Excavator

Reputation: 48

Automatically make all child classes call parent's method

I am currently refactoring a large application.

There is a huge amount of Windows Forms, and they all inherit from one base form. I am unable to debug anything that happens after the first form is ran using Application.Run().

Since the code is a mess, I cannot easily follow the flow when debugging the UI, and do not know which form I am looking at when.

There are too many forms for me to manually create a method for each, so what I want to do is create a method in the parent class which is called by everyone. This method could for example print the form name to console. This way I can create some folder structure in the source code, based on what leads where.

Any suggestions how I could do this using Resharper and/or Visual Studio?

Any input is highly appreciated!

Upvotes: 1

Views: 189

Answers (2)

As I understand and as you said, If all forms Inherit from a base form, they all have components in common. So you can create a Module like bellow and put the methods of this base form.

'This Module you will put all methods from the base form

Module ProcAuxiliar

    Public Sub BaseForm_Sum (ByVal Textbox1 As String, ByVal Textbox2 As String)
        Dim Val1 As Int32 = Convert.ToInt32(Textbox1)
        Dim Val2 As Int32 = Convert.ToInt32(Textbox2)

        MsgBox( Convert.ToString(Val1 + Val2)

    End Sub

    Public Sub BaseForm_decrease (ByVal Textbox1 As String, ByVal Textbox2 As String)
        Dim Val1 As Int32 = Convert.ToInt32(Textbox1)
        Dim Val2 As Int32 = Convert.ToInt32(Textbox2)

        MsgBox( Convert.ToString(Val1 - Val2)

    End Sub

End Module  

In Child Form just call the method from module

'Child Form 1
    Sub BtSumClick(ByVal sender As Object, ByVal e As EventArgs) Handles btSum.Click
        ProcAuxiliar.BaseForm_Sum(Textbox1.Text, Textbox2.Text)
    End Sub

    'Child Form 2
    Sub BtDecreaseClick(ByVal sender As Object, ByVal e As EventArgs) Handles BtDecrease.Click
        ProcAuxiliar.BaseForm_decrease(Textbox1.Text, Textbox2.Text)
    End Sub

Overrideing a method of a baseform in the children and calling the baseform method with more codes:

protected override sub Children_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        MyBase.Children_Load(sender, e)


    MyBase.BaseForm_Load(sender, e)


End Sub

Upvotes: 0

Jakub Dąbek
Jakub Dąbek

Reputation: 1044

If you haven't overriden the OnShown method you can put it in the base form like this :

public /*abstract*/ class BaseForm : Form
{ 
    protected override void OnShown(EventArgs e)
    {
        base.OnShown(e);
        Console.WriteLine($"Entered {this.GetType().Name}");
    }
}

It will be called automatically when any of the forms is shown and print the name of the class to the console using Reflection.

Upvotes: 1

Related Questions