我有几个窗口的应用程序(实际上它的两个几乎相同的窗口具有某些功能)。该功能之一是从 COM 端口读取数据(从称重机读取重量)。问题是,它在第一个窗口上运行完美,但是当我关闭它并打开另一个窗口,然后单击相同的功能(让我们称之为计算重量)时,我收到此错误消息:访问端口“COM1”被拒绝。
代码:
private void calculateWeight_Click(object sender, RoutedEventArgs e)
{
sp = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
tekst = string.Empty;
sp.Open();
sp.WriteLine(((char)5).ToString());
sp.WriteLine(((char)17).ToString());
sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
}
private delegate void UpdateUi(string s);
void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
tekst += sp.ReadExisting();
if (tekst.Contains('S') && tekst.Length > 14)
Dispatcher.Invoke(DispatcherPriority.Send, new UpdateUi(czytajWage), tekst);
}
string tekst = string.Empty;
void czytajWage(string s)
{
string w = "";
for (int i = 5; i < 14; i++)
{
w += s[i];
}
MessageBox.Show(w);
w = "";
tekst = "";
sp.DataReceived -= sp_DataReceived;
}
任何人都可以帮忙吗?;)