PDA

View Full Version : [C#] Evento lettura seriale


aleale97
30-04-2013, 15:27
Ciao a tutti, mi piacerebbe inserire nell'evento per la lettura della SERIALE una modifica a txt1(L'oggetto di un form), ecco il codice:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
static SerialPort SERIAL;

public Form1()
{
InitializeComponent();
SERIAL = new SerialPort();
//SETTINGS
SERIAL.PortName = "COM5";
SERIAL.BaudRate = 9600;
SERIAL.ReadTimeout = 500;
SERIAL.WriteTimeout = 500;
SERIAL.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
SERIAL.Open();
txt1.Text = "SERIAL COM Opened!";
}

private void pictureBox1_Click(object sender, EventArgs e)
{

}

private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();

// !! !! !! !! !! !! !!
txt1.Text = indata;
}

private void button1_Click(object sender, EventArgs e)
{
SERIAL.WriteLine("1");
}

private void btn2_Click(object sender, EventArgs e)
{
SERIAL.WriteLine("2");
}

private void btn3_Click(object sender, EventArgs e)
{
SERIAL.WriteLine("3");
}

private void btn4_Click(object sender, EventArgs e)
{
SERIAL.WriteLine("4");
}
}
}


Tuttavia quando aggiungo la linea preceduta da //!! !! !! !! !! il compilatore ritorna questo errore:

Error 1 An object reference is required for the non-static field, method, or property

Ho cercato online e quasi tutti i risultati parlavano di thread che io non conosco minimamente :doh: Qualcuno che mi aiuti? :D Grazie!

gugoXX
30-04-2013, 22:51
I thread non c'entrano.
Togli tutte le parole "static" dal codice.