【问题标题】:How to access Serial port variable in another file of the project?如何访问项目另一个文件中的串口变量?
【发布时间】:2022-06-13 16:33:46
【问题描述】:

我有一个 C# 项目,在我的 MainWindows.cs 中,我有一个创建函数,该函数通过 COM 端口设置串行通信。我想在同一个项目的另一个文件中访问这个变量,但我似乎做不到。 GUI 是一个使用 .NET 框架的 WPF 应用程序。

public void init() //function that creates the BT connection, it is in the MainWindows.cs
{
     SerialPort myPort = new SerialPort();
     myPort.PortName = "COM8";
     myPort.BaudRate = 9600;

     try
     {
          myPort.Open();
          myPort.WriteLine("Connected");
     }
     catch (Exception ex)
     {
          System.Windows.MessageBox.Show(ex.Message);
     }
}

这是我试图访问 myPort 变量的函数,但它不起作用。

private void running() // This function is in an another file, called Patient_list.cs, which has its own XAML file.
{
      string alert;
      alert = myPort.ReadLine(alert); //Error: The name "myPort" does not exist in the current context
      int to_int = Int32.Parse(alert);
      if (to_int == 2)
      {
            status.Text = "Level 2";
            status.Foreground = Brushes.Orange;
      }
}

【问题讨论】:

    标签: c# wpf serial-port


    【解决方案1】:

    你必须使用类变量:

        private SerialPort _myPort;
    
        public void init() //function that creates the BT connection, it is in the MainWindows.cs
        {
            _myPort = new SerialPort();
            _myPort.PortName = "COM8";
            _myPort.BaudRate = 9600;
    
            try
            {
                _myPort.Open();
                _myPort.WriteLine("Connected");
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
        }
    
        private void running() // This function is in an another file, called Patient_list.cs, which has its own XAML file.
        {
            string alert;
            alert = _myPort.ReadLine(alert); //Error: The name "myPort" does not exist in the current context
            int to_int = Int32.Parse(alert);
            if (to_int == 2)
            {
                status.Text = "Level 2";
                status.Foreground = Brushes.Orange;
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多