Access GUI from event handler

When a byte from the serial port is received, it correctly enters this handler, but my label in the GUI does not change. Edit : Yes, it is in the same class as the GUI. Change 2 Function declaration does not have to be β€œstatic” ... I just copied the example from MSDN edit 3 It works after getting rid of the static declaration and using something like this . Thank you for your help.

private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) { Form1 gui = new Form1(); //main GUI try { SerialPort sp = (SerialPort)sender; string indata = sp.ReadExisting(); //gui.rxLabel.Text = indata; gui.txLabel.Text = "testttingg"; } ....... 
+4
source share
2 answers

Why are you announcing a new instance of your form? Just use your txLabel form

In C #:

this.txLabel.Text = "testing";

In vb.net:

Me.txLabel.Text = "testing"

In the code example you provided, you create a new instance / link to your actual form. Use an existing instance, in addition, use this , not a new instance.

I had to change my question as I noticed that you are using a static method.

Try the following:

  public static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) { Form1 f = (Form1) sender; f.textBox1.Text = "testing"; } private void button1_Click(object sender, EventArgs e) { DataReceivedHandler(this, null); } 

Of course, I just call DataReceivedHandler() from the button event, you can call it from your own event. Point - you need to pass the current instance of this to the function. When a new instance of the form is not created inside the function, just set the link to the current form and use this link to apply the settings to the property (txtBox or Label or something else).

+6
source

It seems you are creating a new instance of Form1 instead of accessing an existing form in memory.

0
source

Source: https://habr.com/ru/post/1379360/


All Articles