为什么应用程序仍在工作,当我关闭它时。
我猜这是由于从串口读取数据引起的。
串行端口号从 ComboBox 中选择。
函数 WriteData 根据来自串行端口的数据更新复选框。
这是摘录:
// Choosing of communication port from ComboBox
private void comboBoxCommunication_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (serialPort.IsOpen)
{
serialPort.DataReceived -= new System.IO.Ports.SerialDataReceivedEventHandler(Recieve);
serialPort.Close();
}
try
{
ComboBoxItem cbi = (ComboBoxItem)comboBoxKomunikacia.SelectedItem;
portCommunication = cbi.Content.ToString();
serialPort.PortName = portCommunication;
serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(Recieve);
serialPort.BaudRate = 2400;
serialPort.Open();
serialPort.DiscardInBuffer();
}
catch (IOException ex)
{
MessageBox.Show(ex.ToString(), "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
// Close the window
private void Window_Closed(object sender, EventArgs e)
{
if (serialPort.IsOpen)
{
serialPort.DataReceived -= new System.IO.Ports.SerialDataReceivedEventHandler(Recieve);
serialPort.Close();
}
}
// Data reading
private delegate void UpdateUiTextDelegate(char text);
private void Recieve(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
if (serialPort.IsOpen)
{
try
{
serialPort.DiscardInBuffer();
char c = (char)serialPort.ReadChar();
Dispatcher.Invoke(DispatcherPriority.Send,
new UpdateUiTextDelegate(WriteData), c);
}
catch(IOException ex)
{
MessageBox.Show(ex.ToString(), "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
// Update of checkboxes
private void WriteData(char c) { ... }