Reputation: 1233
When I'm trying to use a com port in my C# program sometimes the port is open and is used by another program. I want to be specific and generate warning message like this :
"COM1
port is used by other program named SomeApplication
. Do you want to close that program (Note that you may lose data or other consequences)?" -Yes
-No
How to implement this scenario in C#?
Upvotes: 1
Views: 421
Reputation: 942109
This is not supported on Windows, it requires walking undocumented kernel structures that are only accessible in kernel code. Keeping this info hidden is quite intentional, stopping programs from doing exactly what you contemplate doing, killing a process to acquire a resource. And in general is a countermeasure to malware that tries to take advantage of handle recycle attacks.
Your user could use SysInternals' Handle utility to find the process, assuming he doesn't know which ought to be rare. Doing what Handle.exe does in C# code is a very long shot that you should never commit to. It dynamically installs a device driver so it can gain ring 0 permissions to access the kernel data. And the kernel structures have changed between Windows versions and are liable to change again in future versions.
Upvotes: 3