private void RegisterForDeviceChange(bool register, SafeFileHandle fileHandle)
{
if (register)
{
// Register for handle
DEV_BROADCAST_HANDLE data = new DEV_BROADCAST_HANDLE();
data.dbch_devicetype = DBT_DEVTYP_HANDLE;
data.dbch_reserved = 0;
data.dbch_nameoffset = 0;
//data.dbch_data = null;
//data.dbch_eventguid = 0;
data.dbch_handle = fileHandle.DangerousGetHandle(); //Marshal. fileHandle;
data.dbch_hdevnotify = (IntPtr)0;
int size = Marshal.SizeOf(data);
data.dbch_size = size;
IntPtr buffer = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(data, buffer, true);
mDeviceNotifyHandle = Native.RegisterDeviceNotification(mRecipientHandle, buffer, 0);
}
else
{
// close the directory handle
if (mDirHandle != IntPtr.Zero)
{
Native.CloseDirectoryHandle(mDirHandle);
// string er = Marshal.GetLastWin32Error().ToString();
}
// unregister
if (mDeviceNotifyHandle != IntPtr.Zero)
{
Native.UnregisterDeviceNotification(mDeviceNotifyHandle);
}
mDeviceNotifyHandle = IntPtr.Zero;
mDirHandle = IntPtr.Zero;
mCurrentDrive = "";
if (mFileOnFlash != null)
{
mFileOnFlash.Close();
mFileOnFlash = null;
}
}
}