在两个或多个窗口中使用COM端口 [英] Using COM port in two or more windows

查看:106
本文介绍了在两个或多个窗口中使用COM端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好.
我有几个窗口的应用程序(实际上是两个几乎相同的带有某些功能的窗口).该功能之一是从COM端口读取数据(从称重机读取重量).问题是,它在第​​一个窗口上可以正常工作,但是当我关闭它并打开另一个窗口,然后单击相同的功能(让它称其计算重量)时,我得到了此错误消息:
拒绝访问端口"COM1".

代码:

Hello.
I have application with several windows (actually its two almost same windows with some functions). One of that function is reading data from COM port (read weight from weighting machine). Problem is that, it works perfect on first window, but when im closing it and opening another window, then clicking same function (lets call it calculate weight), im getting this error message:
Access to the port ''COM1'' is denied.

Code:

//clicking button 
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);
// entering there if get anything from serial port
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;
//read all data reveived from port and show messagebox with it
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;

}




有人可以帮忙吗? ;)




Anyone can help? ;)

推荐答案

听起来像是在尝试再次打开COM端口之前没有关闭COM端口.
Sounds like you are not closing the COM port, before trying to open it again.


约翰的解决方案将解决您的问题:

使用Windows,只有一个应用程序可以同时打开一个串行端口.这是设计使然.

如果需要从应用程序中的不同模块或窗口访问串行端口,则应仅在一个模块内打开和关闭端口,存储该句柄,并提供返回该句柄的功能.
In addition to John''s solution which will solve your problem:

With Windows, only one application can open a serial port at time. This is by design.

If you need access to a serial port from different modules or windows inside your application, you should open and close the port only within one module, store the handle, and provide a function to return the handle.


这篇关于在两个或多个窗口中使用COM端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆