Access a control of a form from another class C #

0

If you help me please. I have a form with a PictureBox and I want to move it from another class, it compiles but it does not do anything. On Form1 I have my PictureBox1 and from the class I have the following:

public void mover_derecha(object o, DoWorkEventArgs e)
    {
        Form1 p = new Form1();
        p.Location = new Point(p.Location.X + 10, p.Location.Y);

    }

How do I have access to a control from another class?

    
asked by Javier 02.03.2018 в 21:07
source

1 answer

0

If this is how you explain in your comment it is simple, you create a function in your form that moves the image, to the constructor of your other class you pass the instance of your form, and then you call that function. Example

This would be your class

class MiClase
{
    private Form1 form;

    public MiClase(Form1 form)
    {
        this.form = form;
    }

    public void mover_imagen(int x, int y)
    {
        form.mover_imagen(x, y);
    }
}

Here I did what I said before passing the form to the constructor, you can do it like that or simply pass it to the function move_image (Form1 form, int x, int y), so with the first option if you need to work with the form You can keep doing it.

This is the call from another class that is neither your Main Form (Form1), nor the MyClass class, it can be another form for example

    private void button1_Click(object sender, EventArgs e)
    {
        Form1 form = new Form1();
        form1.Show();
        MiClase miclase = new MiClase(form);
        miclase.mover_imagen(12, 120);
    }

Any doubt, click here.

    
answered by 02.03.2018 в 22:07