Eject Memory card from Card Reader C#
I have a custom developed USB card reader. I am using the following code to interact and iterrate over the device:
http://www.codeproject.com/KB/system/usbeject.aspx
The code above provides an 'eject' method using the following line:
Native.CM_Request_Device_Eject_NoUi(device.InstanceHandle, IntPtr.Zero, null, 0, 0);
However this 'eject' method unmounts the entire drive instead of simply ejecting the media card.
Why this is a problem is because I want to 'eject' the media card, then put in a different one. However when the whole reader is ejected i have to unplug/replug the device for it to show back up.
开发者_开发技巧In windows explorer when I right click 'eject' it operates as I am imagining, where it safely removes the memory card but not the card reader.
How can I go about implementing this different type of eject in c#?
I came here accidentally while doing a search on "CM_Request_Device_Eject_NoUi", and saw that it was similar to a solution I'd recently done by pulling together similar pieces of a solution. Forgive the late answers.
Here's what worked for me (this also addresses some issues I've seen on other SO questions regarding AutoEjectVolume
from the Microsoft sample not "doing everything" that the system does when you Safely Remove Hardware using the OS):
- Start with the steps outlined in How to Eject Removable Media in Windows.
- Replace the call to
AutoEjectVolume
with code that is, in effect, the body of theRemoveDrive
method from How to Prepare a USB Drive for Safe Removal. Note that this later work relies heavily on two other CodeProject articles — including the one you referenced in your question — ported to C#.
In 2, I say "in effect" because — in practice — you use the same hVolume
in both solutions, and it makes more sense to do all the checks in the CodeProject RemoveDrive
method before calling LockVolume
, DismountVolume
, or PrepareRemovalOfVolume
in the Microsoft solution, and then call CM_Request_Device_Eject_NoUi
as shown in the CodeProject solution.
A short pseudo-code summary:
- Open the volume with
CreateFile
(CodeProject) - Obtain drive's device instance handle and drive's parent's device instance handle (CodeProject)
- Exit before calling — in particular —
DismountVolume
, if any of the steps above fail (CodeProject) - Call
LockVolume
,DismountVolume
, andPrepareRemovalOfVolume
using thehVolume
returned fromCreateFile
(Microsoft) - You can close the
hVolume
at any time after this - Call
CM_Request_Device_Eject_NoUi
on the drive's parent's device
instance handle (CodeProject)
精彩评论