Hello.
I'm creating a windows program (Visual Studio - C#) to communicate with AVR MCU using serial port. I want to show available serial ports in a ListBox (or combobox) and update the list immediately when a new device is available or a device is disconnected.
Currently I use a "Refresh" button to do that but I want it to be updated automatically.
Also I have a "Connect" button. I want it to be disabled when there isn't any available port and be enabled when some ports are available and user selected one. Currently "Refresh" button updates its state.
I already searched the google but didn't find any "understandable" thing! I'm not very familiar with C# and generally OOP languages (I just wrote C for about 3 years).
What I have tried:
Tried data binding but it didn't work. I think I used it incorrectly.
Current code (simplified):
MainWindow.xaml:
<ListBox x:Name="portList" Grid.Row="1" Margin="0,5"/>
<Button x:Name="refreshButton" Grid.Row="2" Content="Refresh" HorizontalAlignment="Left" Width="75" Click="RefreshButton_Click"/>
<Button x:Name="connectButton" Grid.Row="2" Content="Connect" HorizontalAlignment="Right" Width="75" Click="ConnectButton_Click"/>
ManiWindow.xaml.cs:
public MainWindow()
{
InitializeComponent();
Port_check();
}
private void RefreshButton_Click(object sender, RoutedEventArgs e)
{
Port_check();
}
private void ConnectButton_Click(object sender, RoutedEventArgs e)
{
if (!connected)
{
Ser_Connect();
}
else
{
Ser_Disconnect();
}
}
Serial.cs:
public readonly SerialPort serialPort = new SerialPort
{
BaudRate = 38400,
ReadBufferSize = 8,
WriteTimeout = 500,
ReadTimeout = 5000
};
public static bool connected = false;
public void Port_check()
{
string[] ports = SerialPort.GetPortNames();
if (ports.Length != 0)
{
Ports_available(ports);
}
else
{
No_ports_available();
}
}
private void Ports_available(string[] ports)
{
portList.Items.Clear();
foreach (string port in ports)
{
portList.Items.Add(port);
}
portList.IsEnabled = true;
portList.SelectedIndex = 0;
connectButton.IsEnabled = true;
}
private void No_ports_available()
{
portList.Items.Clear();
portList.IsEnabled = false;
connectButton.IsEnabled = false;
}
public void Ser_Connect()
{
}
public void Ser_Disconnect()
{
if (serialPort.IsOpen)
{
serialPort.DtrEnable = false;
serialPort.Close();
}
connectButton.Content = "Connect";
portList.IsEnabled = true;
refreshButton.IsEnabled = true;
connected = false;
Port_check();
}