问题
I'm working on an application that uses COM port for communication with external controller. When I reboot the PC with communication cable connected, Windows (7) opens the port, without any application running, so I can't access it any more. I tried to close it programatically, but it just stays taken.
Anyone got an idea how can I force it to close, any program I can run before my app, or a way to programatically close it no matter what?
回答1:
I didn't manage to close the port, but after a lot of searching and testing I found what was the source of my problems. I'm posting the solution to help anyone who has the same problem.
Windows identifies devices with constant data stream connected to serial port as serial mouse (in this system it was Microsoft Serial Ballpoint), and tries to install them, taking over the control over the port without any process using it. The solution is to wait for Windows to install the device (check Device Manager under Mouses And Other Pointing Devices) and then DISABLING it. If you uninstall the device it will be installed again, and the problem is back.
Thanks to everyone who tried to help, and I hope others will find this solution useful.
回答2:
No there's no way to force the port to close (see this question). 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 it is a physical COM port on the machine it will be named Serial0, Serial1, ..., or SerialN where COM1 maps to Serial0. If it's a USB to COM adapter I'm not sure what the device ID will be.
You could also try using PortMon to watch for activity on the port. PortMon will show you the process that has the port open.
回答3:
how i resolved was turned off the device with the continuous output, unplug the usb, plug it in again to let windows to detect the com number, then turn the device on again.
回答4:
My guess is that when you close your app and reboot the PC, the external controller is not closing it's side of things gracefully and is left in an undefined state.
When the PC is rebooted the controller is still in this illegal state and it gives the appearance that you cannot open the port on the PC because comms cannot be re-established correctly.
Perhaps the external controller is not handling changes of state of the DTR/DSR lines correctly?
How is the cable between PC and controller wired?
Hard to say much more without knowing any specifics.
回答5:
What I did was to disable the controller, turn it off, restart my computer, turn it on (as soon as windows loads) and go back to enable it. It worked for me with two microcontrollers with this problem.
回答6:
Something like this?
if (serialPort.IsOpen) serialPort.Close();
来源:https://stackoverflow.com/questions/7208094/force-a-com-port-to-close