Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:

C#
//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? ;)
Posted

Sounds like you are not closing the COM port, before trying to open it again.
 
Share this answer
 
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.
 
Share this answer
 
v3
Comments
Jochen Arndt 8-Nov-12 2:59am    
To jlopez788 (who has added a text block to my solution):

Rather than adding your suggestions to existing solutions you should write your own one or write a comment. Just adding some text to solutions from other members without indicating what has been changed or added and why it has been done is impolite.

I rolled back to the initial version because I did not full agree with your suggestion and someone reading the solution would think that I have written all the text.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900