通过C#中的串行端口接收数据或访问端口';COM5和x27;被拒绝
我想将串行端口的数据接收到我的c#程序的富文本框中,但当我选择端口并单击“读取”按钮时,会出现以下错误:访问端口“COM1”被拒绝,我不知道我的错误是什么,请帮我解决。请立即回复,谢谢通过C#中的串行端口接收数据或访问端口';COM5和x27;被拒绝,c#,serial-port,C#,Serial Port,我想将串行端口的数据接收到我的c#程序的富文本框中,但当我选择端口并单击“读取”按钮时,会出现以下错误:访问端口“COM1”被拒绝,我不知道我的错误是什么,请帮我解决。请立即回复,谢谢 using System; using System.Windows.Forms; using System.IO.Ports; using System.Threading; using System.Data; using System.Data.SqlClient; namespace Serial_re
using System;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
using System.Data;
using System.Data.SqlClient;
namespace Serial_receive
{
public partial class Form1 : Form
{
private SqlConnection xConn;
public Form1()
{
InitializeComponent();
xConn = new SqlConnection("Server=.; UID=sa; PWD=123; DataBase=ComportDB;");
viewdata();
}
private void viewdata()
{
DataTable xtable = new DataTable();
new SqlDataAdapter("select * from tbldata", xConn).Fill(xtable);
dataGridView1.DataSource = xtable;
//dataGridView1.Columns[0].Width = 150;
//dataGridView1.Columns[1].Width = 137;
}
private void SaveData()
{
using (var con = xConn)
using (var cmd = con.CreateCommand())
{
cmd.CommandText = "insert into tbldata values(@date, @text)";
string[] lines = richTextBox1.Lines;
foreach (var line in lines)
{
cmd.Parameters.Clear();
cmd.Parameters.Add("@date", SqlDbType.DateTime).Value = DateTime.Now;
// Change your first column type to datetime or datetime2
cmd.Parameters.Add("@text", SqlDbType.NVarChar).Value = line;
// I assume your second column is nvarchar
if (con.State != ConnectionState.Open)
con.Open();
cmd.ExecuteNonQuery();
}
}
}
//search button
private void button1_Click(object sender, EventArgs e)
{
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports)
{
comboBox1.Items.Add(port);
}
}
/// read button
string t;
private void button2_Click(object sender, EventArgs e)
{
t = comboBox1.Text.ToString();
sErial(t);
}
//method
SerialPort sp;
void sErial(string Port_name)
{
sp = new SerialPort(Port_name, 9600, Parity.None, 8, StopBits.One);
sp.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
sp.Open();
}
//
private void DataReceivedHandler(object sender,SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string w = sp.ReadLine();
//string msg = sp.ReadExisting();
if (w != String.Empty)
{
Invoke(new Action(() => richTextBox1.AppendText(w)));
}
}
private void button3_Click(object sender, EventArgs e)
{
SaveData();
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
String a;
a = serialPort1.ReadByte().ToString();
}
}
}
当另一个进程已经打开了端口时,您将得到此异常。因此,您可能需要关闭您正在使用的任何其他程序来测试设备。问题可能与com端口与PC上的其他设备共享IRQ有关,例如com 1可能使用IRQ 4,该IRQ 4也可以分配给声卡。@Graffito和Hans Passant这不起作用。你们能告诉我,如果我使用的是com1端口,那么我可以通过其他程序中的同一端口接收数据吗。例如,如果我通过Com 1发送“abc”,那么Com 1是否可能同时接收“abc”?可能是您自己的程序导致了问题。只呼叫按钮2一次。如果不关闭串口,就不能打开串口两次。@jdweng您的意思是可以在同一个端口上同时发送和接收数据吗?