我已经编写了以下代码,在主窗体加载时配置串口。在第一次运行时,当打开端口时,它会给出IOException
,指出参数不正确。但是当我重新启动应用程序时,它就正常工作了。异常仅在计算机启动后第一次运行应用程序时出现,然后在计算机下一次重启之前都可以正常工作。
private void Main_Load(object sender, EventArgs e)
{
this.serialPort1.PortName = "COM3";
this.serialPort1.BaudRate = 9600;
this.serialPort1.DataBits = 8;
this.serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort1_DataReceived);
this.serialPort1.Open(); //Exception comes here
this.serialPort1.WriteLine("AT#cid=1" + System.Environment.NewLine);
}
异常详情:
用户代码无法处理System.IO.IOException异常
消息="参数不正确。\r\n" 来源="System"
堆栈跟踪: 在 System.IO.Ports.InternalResources.WinIOError(Int32 errorCode, String str) 在 System.IO.Ports.InternalResources.WinIOError() 在 System.IO.Ports.SerialStream.set_RtsEnable(Boolean value) 在 System.IO.Ports.SerialStream..ctor(String portName, Int32 baudRate, Parity parity, Int32 dataBits, StopBits stopBits, Int32 readTimeout, Int32 writeTimeout, Handshake handshake, Boolean dtrEnable, Boolean rtsEnable, Boolean discardNull, Byte parityReplace) 在 System.IO.Ports.SerialPort.Open() 在 JKamdar.Main.Main_Load(Object sender, EventArgs e) in D:\Project\JKamdar\JKamdar\Main.cs:line 264 在 System.Windows.Forms.Form.OnLoad(EventArgs e) 在 System.Windows.Forms.Form.OnCreateControl() 在 System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible) 在 System.Windows.Forms.Control.CreateControl() 在 System.Windows.Forms.Control.WmShowWindow(Message& m) 在 System.Windows.Forms.Control.WndProc(Message& m) 在 System.Windows.Forms.ScrollableControl.WndProc(Message& m) 在 System.Windows.Forms.ContainerControl.WndProc(Message& m) 在 System.Windows.Forms.Form.WmShowWindow(Message& m) 在 System.Windows.Forms.Form.WndProc(Message& m) 在 System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) 在 System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) 在 System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) 内部异常: