检测可移动介质弹出请求的Windows服务弹出、介质、Windows

2023-09-06 07:19:46 作者:个性的

我有一个Windows服务在C#编写的.NET 2.0框架,使用FileSystemWatcher的监视改变某些目录。一些这些目录可以是在可移动介质,诸如USB驱动器。当一个新的驱动器插入到系统中,我得到通知通过WMI查询,可以建立一个新的FileSystemWatcher的。所有这一切运作良好。

I have a Windows service written in C# with the .NET 2.0 framework that uses the FileSystemWatcher to monitor certain directories for changes. Some of these directories may be on removable media, such as a USB drive. When a new drive is plugged into the system, I get notification through a WMI query and can set up a new FileSystemWatcher. All that works well.

困难的是,我希望用户能够弹出使用Windows的驱动器安全删除硬件的应用程序,但Windows报告说,该驱动器正忙,因为我通过FileSystemWatcher的监视它,并告诉用户驱动器不能被删除。

The difficulty is that I want the user to be able to eject the drive using the Windows "Safely Remove Hardware" app, but Windows reports that the drive is busy because I'm monitoring it via FileSystemWatcher, and tells the user the drive cannot be removed.

我的问题的话,是怎么能在我的Windows服务知道当用户请求排出,这样我可以删除我的文件系统监控,并允许申请成功?

My question, then, is how can my Windows Service know when the user requests ejection, so that I can remove my file system monitor and allow the request to succeed?

推荐答案

您需要注册接收设备删除查询广播事件(DBT_DEVICEQUERYREMOVE),通过RegisterDeviceNotification的Windows API,作为解释的这里。

You need to register to receive the device removal query broadcast event (DBT_DEVICEQUERYREMOVE), via the RegisterDeviceNotification Windows API, as explained here.

据我所知,没有哪个包装此功能,所以你需要用对做长手.NET Framework类/ Invoke的。

As far as I know there is no .NET Framework class which wraps this functionality, so you'll need to do it long-hand using p/Invoke.