I want to write a program for VC. It does not work to forward the log to the form. I tried it differently already, but all the time I swear that Form1.richTextBox1.Text unavailable due to the level of protection. Here are the pieces of code, if necessary, I can throw it off completely:

Form1.cs

 public static void log(string text) { richTextBox1.Text = text; } 

VkAuth.cs

 string done = net.Get(String.Format("https://login.vk.com/?act=login&email={0}&pass={1}&lg_h={2}", login, pass, pars)).ToString(); int status = CheckAuth(done);//Запрос формируется заново? if (status == 1) // если всё успешно { Form1.log("Авторизация прошла успешно"); } if (status == 2) // если аккаунт заблокирован { Form1.log("Аккаунт заблокирован"); } if (status == 3) //Проверка валидности данных { Form1.log("Проверьте введенные данные"); } 
  • 2
    Why do you have a log() method declared static? - rdorn
  • If your form is the only one, then organize a singleton and access it through a static method. - Dmitry Chistik

2 answers 2

You can create a singleton if the form (instance) is one per project and access the form via this singleton using static methods or properties.


Initialize Singleton

 public partial class MyForm : Form { public static MyForm LastInstance {get; protected set;} public MyForm() { ... LastInstance = this; } //Если текстбокс объявлен как защищенный public static SetTextLog(string text) { LastInstance.ТекстБокс.Text = text; } } 

Calling the Singleton Method

 //Если текстбокс объявлен как защищенный MyForm.SetTextLog("Какая-то строчка"); //Если текстбокс публичный MyForm.LastInstance.ТекстБокс.Text = "Какая-то строчка"; 

    From the static method there is no access to non-static elements of the class, which elements is your richTextBox. Make an event in your VkAuth window, and in Form1 just subscribe to a non-static function (IMHO). Or transfer in some other way the information you need (for example, through the field).

    Form1.cs

     private log(string txt) { richTextBox1.Text = txt; } VkAuth authWnd = new VkAuth(); authWnd.NewMessage += log; authWnd.Show(); 

    VkAuth.cs

     public event Action<string> NewMessage; public VkAuth() { ... NewMessage += new delegate(string) {}; } //Какая то функция { string done = net.Get(String.Format("https://login.vk.com/?act=login&email={0}&pass={1}&lg_h={2}", login, pass, pars)).ToString(); int status = CheckAuth(done);//Запрос формируется заново? if (status == 1) // если всё успешно { NewMessage("Авторизация прошла успешно"); } if (status == 2) // если аккаунт заблокирован { NewMessage("Аккаунт заблокирован"); } if (status == 3) //Проверка валидности данных { NewMessage("Проверьте введенные данные"); } } 
    • you can use NewMessage?.Invoke("Аккаунт заблокирован") and not declare an empty delegate in the constructor - Dmitry Chistik
    • @Dmitry Chistik, in principle, yes, but somehow I tried to make it easier for a beginner. - Mirdin