FrenkyB
FrenkyB

Reputation: 7197

Pass windows form instance as parameter

I have windows form which is calling another class's method and need to be passed as parameter.

public partial class Form1 : Form
    {                
        private myClass _myClass;       

        public Form1()
        {
            InitializeComponent();
            _myClass = new myClass(//pass this instance - Form1 - as parameter)
        }
    }

But I don't know how to pass Form1 instance as parameter? I need to do this, because this other class is creating system tray icon and menu strip and is able to close the parent form.

Upvotes: 2

Views: 13250

Answers (5)

Szymon
Szymon

Reputation: 43023

Simply declare a parameter of type Form in the other's class constructor:

public class myClass
{
    private Form otherForm;

    public myClass(Form form) 
    {
        otherForm = form;
    }
}

and call it from within Form1:

_myClass = new myClass(this);

Upvotes: 3

Ehsan
Ehsan

Reputation: 32661

I can't figure out what you want to achieve. but if you just want to pass this form than you can use this.

_myClass = new myClass(this);

Upvotes: 2

Ann L.
Ann L.

Reputation: 13965

Unless I'm missing something, this ought to be fairly straightforward:

    public Form1(myClass instance)
    {
        InitializeComponent();
        _myClass = instance;
    }

Upvotes: 0

Grant Winney
Grant Winney

Reputation: 66439

You'd just do:

_myClass = new myClass(this);

And then change the constructor in myClass:

public class myClass
{
    private Form1 theForm;

    public myClass(Form1 theForm)
    {
        this.theForm = theForm;
    }

    ...
}

Now you can access the form from within the class. I think I'd avoid doing this though. Try to leave the form in charge of calling the class and determining when it should close itself.

Having the class hold a reference back to the form that instantiated it, and closing it from within the class seems like it could lead to confusion and maintainability issues down the road.

Upvotes: 6

Dimitar Dimitrov
Dimitar Dimitrov

Reputation: 15138

Sure you can:

_myClass = new myClass(this);

Upvotes: 1

Related Questions