简体   繁体   中英

What program or process is using a specific serial port in C#

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#?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM