Good day. I need to change the textbox value from another class, I was able to figure out how to do this with the help of this video https://www.youtube.com/watch?v=D9qcKV4j75U . The only problem is that I was able to change the textbox value when I clicked the button. Here is a small example:

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { private Worker _worker; public Form1() { InitializeComponent(); sendMessageButton.Click += Button1_Click; } private void Button1_Click(object sender, EventArgs e) { _worker = new Worker(); _worker.SendMessage += _worker_SendMessage1; Thread thread = new Thread(_worker.Work); thread.Start(); if (_worker != null) _worker.SendMessageToTB(); } private void _worker_SendMessage1(string mess) { ChatTextBox.Invoke((MethodInvoker)(() => ChatTextBox.Text += mess)); } } public class Worker { private string mess = "Кажется, ты что-то нажал...\r\n"; private bool _sendMessage = false; public void SendMessageToTB() { _sendMessage = true; } public void Work() { if (_sendMessage) { SendMessage(mess); _sendMessage = false; } } public event Action<string> SendMessage; } } 

For my own program, you need to make sure that the value of the text box changes without pressing any button. The point is that as soon as the server receives a message from the user, he (the server) should not only send this message to all other connected users (the server.BroadcastMessage method is responsible for this), but also output its form to the textbox. Unfortunately, I myself still can not figure it out, the text in the textbox is not displayed in any way. Here is the program code. Server class:

 public class ClientObject { public event Action<string> SendMessage; internal string Id { get; private set; } internal NetworkStream Stream { get; set; } string userName; TcpClient client; ServerObject server; public ClientObject() { } public ClientObject(TcpClient tcpClient, ServerObject serverObject) { Id = Guid.NewGuid().ToString(); client = tcpClient; server = serverObject; server.AddConnection(this); } public void Process() { try { // Возвращаем объект NetWorkStream, используемый для отправки и получения данных Stream = client.GetStream(); // Получаем имя пользователя userName = GetMessage(); string message = userName + " вошел в чат."; // Рассылаем сообщение о входе в чат всем подключенным пользователям server.BroadcastMessage(message, Id); // отправляем сообщение всем подключенным пользователям SendMessage(message); // Данный текст должен быть записан в textbox формы // Получаем данные от пользователя while (true) { try { message = GetMessage(); message = string.Format($"{userName}: {message}"); server.BroadcastMessage(message, Id); SendMessage(message); // Данный текст должен быть записан в textbox формы } catch { message = userName + " покинул чат."; server.BroadcastMessage(message, Id); SendMessage(message); // Данный текст должен быть записан в textbox формы break; } } } finally { // Удаляем пользователя из списка подключенных пользователей и закрываем поток с соединением server.RemoveConnection(Id); Close(); } } } 

Form Class:

 namespace Server { public partial class Form1 : Form { static ServerObject server; static Thread listenerThread; private ClientObject cl = new ClientObject(); public Form1() { InitializeComponent(); cl.SendMessage += Cl_SendMessage; // Подписываемся на событие try { server = new ServerObject(); listenerThread = new Thread(new ThreadStart(server.Listen)); listenerThread.Start(); // старт потока } catch (Exception exc) { server.Disconnect(); } } private void Cl_SendMessage(string mess) { chatLogTB.Invoke((MethodInvoker)(() => chatLogTB.Text += mess)); } } } 

I really hope that someone will help or tell you how to properly implement what I need. PS here is a link to the entire project, maybe you will find the error: http://rgho.st/8gTqYzFrP

  • chat.LogTB.Dispatcher.Invoke (new Action (() => {chatLogTD.Text + = mess})); - Morgomirius

2 answers 2

  1. You can take advantage of the events.

You sign 1 form for events of another form and handle the reaction to this event.

They say that this is the right way.

  1. You can create an open method on a form and use it to interact with another form.

    You need to create an object of the form class that you want to change in the class from where you need to change the form, and then with the help of this object you will change the parameters of the desired form. For example:

     // Класс Form2 Form1 form = new Form1(); form.TextBox1 = "Hello, World!"; 

    (in this case, Form1 is the form you want to change, and form.TextBox1 is your TextBox.)

    • it doesn't work like that. - Julian Del Campo