开发者

c# cannot be referenced from a static function

开发者 https://www.devze.com 2023-01-03 13:40 出处:网络
c# newbie h开发者_StackOverflow社区ere. seems like this user gave me a very good solution for my problem:

c# newbie h开发者_StackOverflow社区ere.

seems like this user gave me a very good solution for my problem:

serialport error

but i have no clue how to code up what he suggested. can you please help?


This will compile fine. You'll have to give thePort real settings, of course.

namespace csWinFormsTest
{
    public partial class Form1 : Form
    {
        static System.IO.Ports.SerialPort thePort;
        public Form1()
        {
            InitializeComponent();
            thePort = new System.IO.Ports.SerialPort("COM1");
        }

        static void fcn()
        {
            MessageBox.Show(thePort.PortName);
        }
    }
}


public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private static SerialPort serialPort1;
        public class ThreadWork
        {

            public static void DoWork()
            {
                serialPort1 = new SerialPort();
                //stuff
            }
        }

        private void Form1_Load(object sender, EventArgs 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")));
        }
    }

You don't really need to have DoWork() static though.

0

精彩评论

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