注册 登录
编程论坛 ASP.NET技术论坛

asp.net中serial port与虚拟串口连接的问题

骨子里的认真 发布于 2013-09-27 17:55, 628 次点击
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            serialPort1.PortName = "COM1";
            serialPort1.BaudRate = 9600;
             serialPort1.Open();
            byte[] data = Encoding.Unicode.GetBytes(textBox1.Text);
            string str = Convert.ToBase64String(data);
            serialPort1.WriteLine(str);
            MessageBox.Show("数据发送成功!", "系统提示");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            byte[] data = Convert.FromBase64String(serialPort1.ReadLine());
            textBox2.Text = Encoding.Unicode.GetString(data);
            serialPort1.Close();
            MessageBox.Show("数据接收成功!", "系统提示");
        }

    }
错误提示:

未处理 System.InvalidOperationException
  Message="端口被关闭。"
  Source="System"
  StackTrace:
       在 (String value)
       在 Ex13_01.Form1.button2_Click(Object sender, EventArgs e) 位置 F:\数据库开发\SQL数据库\各种练习\Ex13_01\Ex13_01\Form1.cs:行号 32
       在 System.Windows.Forms.Control.OnClick(EventArgs e)
       在 System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       在 System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       在 System.Windows.Forms.Control.WndProc(Message& m)
       在 System.Windows.Forms.ButtonBase.WndProc(Message& m)
       在 System.Windows.Forms.Button.WndProc(Message& m)
       在 System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       在 System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       在 System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       在 System.Windows.Forms.(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       在 System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       在 System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       在 Ex13_01.Program.Main() 位置 F:\数据库开发\SQL数据库\各种练习\Ex13_01\Ex13_01\Program.cs:行号 17
       在 System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       在 Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       在 System.Threading.ThreadHelper.ThreadStart()
不懂怎么处理,求指点
3 回复
#2
Aviva_Wang2013-09-30 08:31
空值异常,他有显示行号,你可以看看是在哪边,如果是空值,你上面的那种数据转换是会报错的。
我想说,我不懂串口
#3
骨子里的认真2013-09-30 10:24
回复 2楼 Aviva_Wang
我也不懂串口,刚开始学,什么都不会,也不会改错。这个好像不是空值的问题,我改了,但又有新问题了,端口打开时无法设置“PortName”。不过还是谢谢你。
#4
3037709572013-09-30 17:54
非法操作,端口被关闭!
1