-1

Inside my main Form: partial class Form1 : Form

I have this method: public void SendLog();

Inside another class: class Player

I have a method which I want to call that SendLog() from Form1

public void Print()
{
    Form1.SendLog();   // Error: An object reference is required for the non-static field, method, or property 'Form1.SendLog(string)'  
}

How do I do that ? My Player class contains many calls to SendLog() so I prefer to have a global instance of Form1 declared in the beginning so that I can use something like f.SendLog(); rather than passing Form1 instance to method every call.

Like this:

class Player
{
    public Form1 f = Form1;
    public void Print()
    {
        f.SendLog();
    }
}
samyung_c
  • 23
  • 1
  • 6
  • I think it does, but then that code must be put inside every method that calls SendLog(). Is there any way I can declare a global reference using that code ? – samyung_c Jul 18 '21 at 16:06
  • Sure, if there is is at any time exacty one instance of `Form1` (this is called a singleton), add a `public static Form1 Instance { get; }` to the `Form1` class and initialize it in the Form1 constructor. Then you can call it from everywhere as `Form1.Instance.Whatever();`. – Klaus Gütter Jul 18 '21 at 16:09

1 Answers1

-1

One method is that send the Form1 class as a parameter to the player class.

Like the following:


public partial class Form1 : Form
{
   public Form1()
   {
      InitializeComponent();
   }
   
   //...................
   Player player = new Player(this);
   player.Show();
}

Player Class

class Player
{

    Form1 f;
    public Player(Form1 _f)
    {
       f = _f;
    }
    public void Print()
    {
        f.SendLog();
    }
}

Another way is to use Application.OpenForms which Gets a collection of open forms owned by the application.

var form1 = Application.OpenForms.OfType<Form1>().Where(x => x.Name == "formName").FirstOrDefault();
form1.SendLog();

or use

foreach (Form frm in Application.OpenForms)
{
    if(frm.Name == "formName")
    {
       frm.SendLog();
       break;
    }
}
 
       
Meysam Asadi
  • 6,438
  • 3
  • 7
  • 17