Click here to Skip to main content
15,891,788 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi,
I want to open and close the serial port by clicking same button.

Here's my code.

C#
bool a = sp.IsOpen;
                    if (a == true)
                    {
                        
                        this.sp.Close();
                    }
                    else
                    {
                        this.sp.Open();
                    }

but its not working. It is not closing the connection instead it is showing access denied to that specific port.

What I have tried:

bool a = sp.IsOpen;
if (a == true)
{

this.sp.Close();
}
else
{
this.sp.Open();
}

i have tried the same in switch case also. still the result is same.
Posted
Updated 17-May-16 4:54am
Comments
CHill60 2-May-16 8:00am    
The user you are running this as does not have permissions to close the port.
George Jonsson 2-May-16 8:15am    
Are you sure you get the exception when you close the port. Access denied exception is usually thrown when trying to open a port that is already opened, either by your process or some other process on the machine.
Jochen Arndt 2-May-16 8:44am    
Are sp and this.sp referencing the same SerialPort instance?

If not, you may probably try to open an already opened port which will fail as mentioned by George Jonsson.
Sinisa Hajnal 2-May-16 9:21am    
remove a variable and do if (this.sp.IsOpen). You don't need == true for boolean and this way you're sure you're referencing the same item you're opening/closing.

Also, the error implies that user under which the app is running has no rights to finish the operation. Check with the admin user.
Sergey Alexandrovich Kryukov 2-May-16 9:25am    
if (a == true) tells the tail. Are you sure you understand what you are doing?
a is already Boolean, and then you compare it with another Boolean. Why?
Do you understand that
a == (a == true) for any a?
If you did, you would probably write if (a)...
—SA

1 solution

why you will not check by its Text property like this-

1)give btn_1.text="OPEN"(Initially)
2) on clicking the button on click event handler change the text to "CLOSE"

Now you can do your work like this-

if(btn1.text=="OPEN")
{
this.sp.Close();//do any thing
}
else
{
//Do something
}
 
Share this answer
 
v2
Comments
George Jonsson 17-May-16 13:05pm    
Changing the button text is not a bad idea, but comparing text is.

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