I have device which is connect to PC via USB Serial communication. I am performing following steps
So I think I have some way to close communication port forcefully.
There is no way to force another process to close the port so you can take it. But Windows isn't opening up the port by itself - some other application running in the background is probably doing it. Download Process Explorer and use the "Find Handle or DLL" on the Find menu to find the process with the com port open.
If you are communicationg with your hardware over a serial port and using a SerialEventListener, then I think a Serial.DATA_BREAK(Dont remember the exact name) event occurs. You could catch this in the SerialEvent method and close the connection from your program to your port. Hope this helps you to forcibly close your connection at the time of disconnection of the hardware.
I have found solution though it can not be called standard solution but though i don't have any problem with that solution because it solves my problem the solution is as per belove step
FIRST STEP:-
class clsRS232 : IDisposable
{
private SerialPort myPort;
public clsRS232()
{
myPort = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
}
public void OpenPort()
{
myPort.Open();
}
public void SendFunc(string str)
{
myPort.Write(str);
}
public string ReadFunc()
{
return myPort.ReadExisting();
}
public void Dispose()
{
myPort.Dispose();
}
}
SECOND STEP:-
using (clsRS232 mySerialPort = new clsRS232())
{
lock (mySerialPort)
{
mySerialPort.OpenPort();
mySerialPort.SendFunc(commandArg);//here "commandArg" is command or data you want to send to serial port
this.serialPortObj_DataReceived(mySerialPort.ReadFunc()); //here "serialPortObj_DataReceived()" is a user define method where received data will be passed
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With