简体   繁体   中英

Access a method from another form

In my main form I have this method to stop a timer:

public  void resettimer()
{
    ShutdownTimer.Stop();
}

Now I need to activate this methode when a buttom was clicked on another form. This is how i coded it:

private void btn_doorgaan_Click(object sender, EventArgs e)
{ 
    //bib_main is how the first form is called

    Bib_main MainMenu = new Bib_main();
    MainMenu.resettimer();
}

This is also what I find on the internet but nothing happens, the methode never triggers.

Can u guys tell me what i am doing wrong or if their is a better way to stop the timer in the other form when the buttom is clicked?

You can't just make a new Bib_main object and call the method on it. You need to call the method on your existing Bib_main .

When you create the new form, you should include a reference to your existing form (the one with the method). Than with that reference you can call the method, instead of creating a new instance of Bib_main.

EDIT:

Constructor of the form should look like this:

private Bib_Main _mainForm;

public SomeForm(Bib_Main mainForm)
{
    // store the reference to a field
    _mainForm = mainForm;
}

When creating the new form in the main form:

SomeForm newForm = new SomeForm(this);

Then you can just call it like:

_mainForm.resettimer();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM