开发者

serial port does not exist in current context: c#

开发者 https://www.devze.com 2023-01-03 13:36 出处:网络
here\'s the code: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data;

here's the code:

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

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public class ThreadWork
        {
            private static SerialPort serialPort1;
            public static void DoWork()
            {
                serialPort1.Open();
                serialPort1.Write("AT+CMGF=1\r\n");
                //Thread.Sleep(500);
                serialPort1.Write("AT+CNMI=2,2\r\n");
                //Thread.Sleep(500);
                serialPort1.Write("AT+CSCA=\"+4790002100\"\r\n");
                //Thread.Sleep(500);
                serialPort1.DataReceived += serialPort1_DataReceived_1;
            }
        }

        private void Form1_Load(object sender, E开发者_运维技巧ventArgs e)
        {
            ThreadStart myThreadDelegate = new ThreadStart(ThreadWork.DoWork);
            Thread myThread = new Thread(myThreadDelegate);
            myThread.Start();
        }

        private void serialPort1_DataReceived_1(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            string response = serialPort1.ReadLine();
            this.BeginInvoke(new MethodInvoker(() => textBox1.AppendText(response + "\r\n")));
        }
    }
}

and i get an error on this line:

string response = serialPort1.ReadLine();

it says::

Error 1 The name 'serialPort1' does not exist in the current context C:\Users\alexluvsdanielle\AppData\Local\Temporary Projects\WindowsFormsApplication1\Form1.cs 44 31 WindowsFormsApplication1

what am i doing wrong?


Move the definition of serialPort1 up a few lines, into the Form1 class instead of the Form1.ThreadWork class.

WHere it is at the moment, in the Form1.ThreadWork class, it can only seen by members of the Form1.ThreadWork class, not the Form1 class.


serialport1 exists on the class ThreadWork, not in your form

0

精彩评论

暂无评论...
验证码 换一张
取 消