A
A
Anton Shamov2017-09-19 21:53:34
WPF
Anton Shamov, 2017-09-19 21:53:34

How to make an open COM port available inside the entire wpf C# project?

Good day!
I ask for help in understanding, and maybe in resolving the issue that interests me.
I'm still quite green in programming (3 days of study), before that I wrote only sites in php. I am making a small program (wpf) for working with a COM port, there is a main window in the code of which the desired COM port opens and there is a console where the answer and a field with a button for sending commands are displayed. There was a need to transfer the console and the input field with the button to another window. Those. open the port in the main window, and work with it in another window.

MainWindow

SerialPort currentSerial = new SerialPort();
currentSerial.PortName = port_combobox.Text;
currentSerial.BaudRate = 115200;
currentSerial.Open(); 

ConsoleWindow

private void send_button_Click(object sender, RoutedEventArgs e)
{
      currentSerial.WriteLine(msg_textbox.Text); //Собственно здесь надо как-то инициализировать открытый порт, ругается что имя "currentSerial" не существует в данном контексте
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
Peter, 2017-09-20
@petermzg

So write a separate class for working with the COM port, create an instance of it and pass it to the form constructors.

D
Dmitry Chernyakov, 2017-09-21
@Kubatai

The easiest way in the forehead is to make a static public class with a COM port and wrap the main tools for working with it in methods (optional).

public static class COM
{
  public static SerialPort CurrentSerial {get; private set; }

  public static InitSerialPort(string text, int baudRate)
  {
    CurrentSerial = new SerialPort();
    CurrentSerial.PortName = text;
    CurrentSerial.BaudRate = baudRate;
    CurrentSerial.Open(); 
  }
}

If you have many ports then use IList;

R
Roman, 2017-09-21
@yarosroman

Dependency Injection to help you, many IoC containers have the ability to create singletons.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question