我正在尝试在虚拟串口上写。这是我的代码:
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);
}
}
}
这是我的输出:
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).
为什么我收到此错误?端口正确打开和关闭,参数也正确。有人知道我的错误在哪里吗?