Reputation: 1843
I am trying to write on a virtual serial port. This is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System;
using System.IO.Ports;
using System.Threading;
namespace MyWPFApp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
///
public partial class MainWindow : Window
{
static private SerialPort MyPort;
public MainWindow()
{
InitializeComponent();
MyPort = new SerialPort("COM4");
OpenMyPort();
}
private void btn_Click(object sender, RoutedEventArgs e)
{
try
{
if (!MyPort.IsOpen)
MyPort.Open();
}
catch (Exception ex)
{
Console.WriteLine("Error opening my port: {0}", ex.Message);
}
Console.WriteLine(MyPort.IsOpen);
try
{
MyPort.Write("Hello");
}
catch (Exception ex)
{
Console.WriteLine("Error writing:", ex.Message);
}
MyPort.Close();
Console.WriteLine(MyPort.IsOpen);
}
}
}
This is my Output:
True
A first chance exception of type 'System.IO.IOException' occurred in System.dll
Additional information: The parameter is incorrect.
The thread 0x195c has exited with code 259 (0x103).
Error writting:
False
The thread 0x19d4 has exited with code 259 (0x103).
The thread 0x1b18 has exited with code 259 (0x103).
The program '[3080] MyWPFApp.vshost.exe' has exited with code 0 (0x0).
Why I got this error?The port is correctly opened and closed and the parameters are correct too. Does someone knows where is my error?
Upvotes: 0
Views: 2199