Today I researched how to implement in C# a method that forces a COM port to close when it is open by another process. This was found to be a complex task that involves using undocumented Win32 API functions. I didn’t finish it because I found another way to workaround the problem but the idea is the following:
1) Enumarate all Win32 processes.
2) In each process enumerate all its handles and find the handle to be closed (e.g. \Device\Serial0).
3) Close the handle.
The first task is trivial. We can use System.Diagnostics.Process.GetProcesses(). The second is possible with the Windows NT undocumented function NtQuerySystemInformation. The third task is simple. Once we have the process ID (pid) and the handle of the open COM port, we can close it with the following CloseHandleEx function:
Posted by nakov in blog

