473,888 Members | 1,599 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How can I detect cdrom/usb device insertions?

I am writing a C# app that needs to periodically poll for cdroms and usb
storage device insertions. I've looked at the WMI functions but haven't
found anything all that useful. The closest is Win32_DiskDrive , but it
doesn't seem to return any information on cdrom devices. I suspect there
might be a Win32 API call, but I haven't found any info yet using Google. Is
there a way to achieve this in C#?

Nov 16 '05 #1
9 37217
Paul,

Have a look at this CodeProject article:
http://www.codeproject.com/dotnet/de...umemonitor.asp

Alexander

"Paul Steele" <pa*********@ac adiau.ca> wrote in message
news:uA******** ******@TK2MSFTN GP12.phx.gbl...
I am writing a C# app that needs to periodically poll for cdroms and usb
storage device insertions. I've looked at the WMI functions but haven't
found anything all that useful. The closest is Win32_DiskDrive , but it
doesn't seem to return any information on cdrom devices. I suspect there
might be a Win32 API call, but I haven't found any info yet using Google.
Is there a way to achieve this in C#?

Nov 16 '05 #2
Hi,
I'm not sure whether you can do it in C#, i.e you have any direct classes
for this, but you have Win32 API's for detecting the cdroms insertions. The
following data may be helpful to you. Courtesy, MSDN

Detecting Media Insertion or Removal
Windows sends all top-level windows a set of default WM_DEVICECHANGE
messages when new devices or media (such as a CD or DVD) are added and become
available, and when existing devices or media are removed. You do not need to
register to receive these default messages. See the Remarks section in
RegisterDeviceN otification for details on which messages are sent by default.
The messages in the code example below are among the default messages.

Each WM_DEVICECHANGE message has an associated event that describes the
change, and a structure that provides detailed information about the change.
The structure consists of an event-independent header, DEV_BROADCAST_H DR,
followed by event-dependent members. The event-dependent members describe the
device to which the event applies. To use this structure, applications must
first determine the event type and the device type. Then, they can use the
correct structure to take appropriate action.
When the user inserts a new CD or DVD into a drive, applications receive a
WM_DEVICECHANGE message with a DBT_DEVICEARRIV AL event. The application must
check the event to ensure that the type of device arriving is a volume (the
dbch_devicetype member is DBT_DEVTYP_VOLU ME) and that the change affects the
media (the dbcv_flags member is DBTF_MEDIA).

When the user removes a CD or DVD from a drive, applications receive a
WM_DEVICECHANGE message with a DBT_DEVICEREMOV ECOMPLETE event. Again, the
application must check the event to ensure that the device being removed is a
volume and that the change affects the media.

The following code demonstrates how to check for insertion or removal of a
CD or DVD.
#include <windows.h>
#include <dbt.h>

void Main_OnDeviceCh ange (HWND hwnd, WPARAM wParam, LPARAM lParam);
char FirstDriveFromM ask (ULONG unitmask); //prototype

/*------------------------------------------------------------------
Main_OnDeviceCh ange (hwnd, wParam, lParam)

Description
Handles WM_DEVICECHANGE messages sent to the application's
top-level window.
--------------------------------------------------------------------*/

void Main_OnDeviceCh ange (HWND hwnd, WPARAM wParam, LPARAM lParam)
{
PDEV_BROADCAST_ HDR lpdb = (PDEV_BROADCAST _HDR)lParam;
char szMsg[80];

switch(wParam)
{
case DBT_DEVICEARRIV AL:
// Check whether a CD or DVD was inserted into a drive.
if (lpdb -> dbch_devicetype == DBT_DEVTYP_VOLU ME)
{
PDEV_BROADCAST_ VOLUME lpdbv = (PDEV_BROADCAST _VOLUME)lpdb;

if (lpdbv -> dbcv_flags & DBTF_MEDIA)
{
wsprintf (szMsg, "Drive %c: Media has arrived.\n",
FirstDriveFromM ask(lpdbv ->dbcv_unitmask) );

MessageBox (hwnd, szMsg, "WM_DEVICECHANG E", MB_OK);
}
}
break;

case DBT_DEVICEREMOV ECOMPLETE:
// Check whether a CD or DVD was removed from a drive.
if (lpdb -> dbch_devicetype == DBT_DEVTYP_VOLU ME)
{
PDEV_BROADCAST_ VOLUME lpdbv = (PDEV_BROADCAST _VOLUME)lpdb;

if (lpdbv -> dbcv_flags & DBTF_MEDIA)
{
wsprintf (szMsg, "Drive %c: Media was removed.\n",
FirstDriveFromM ask(lpdbv ->dbcv_unitmask) );

MessageBox (hwnd, szMsg, "WM_DEVICECHANG E", MB_OK);
}
}
break;

default:
/*
Process other WM_DEVICECHANGE notifications for other
devices or reasons.
*/
;
}
}

/*------------------------------------------------------------------
FirstDriveFromM ask (unitmask)

Description
Finds the first valid drive letter from a mask of drive letters.
The mask must be in the format bit 0 = A, bit 1 = B, bit 3 = C,
etc. A valid drive letter is defined when the corresponding bit
is set to 1.

Returns the first drive letter that was found.
--------------------------------------------------------------------*/

char FirstDriveFromM ask (ULONG unitmask)
{
char i;

for (i = 0; i < 26; ++i)
{
if (unitmask & 0x1)
break;
unitmask = unitmask >> 1;
}

return (i + 'A');
}

Pradeep Kumar.R

"Paul Steele" wrote:
I am writing a C# app that needs to periodically poll for cdroms and usb
storage device insertions. I've looked at the WMI functions but haven't
found anything all that useful. The closest is Win32_DiskDrive , but it
doesn't seem to return any information on cdrom devices. I suspect there
might be a Win32 API call, but I haven't found any info yet using Google. Is
there a way to achieve this in C#?

Nov 16 '05 #3
This is definitely a good starting point. Unfortunately it does not detect
USB key insertions...

"Alexander Shirshov" <al*******@omni talented.com> wrote in message
news:ef******** ******@TK2MSFTN GP09.phx.gbl...
Paul,

Have a look at this CodeProject article:
http://www.codeproject.com/dotnet/de...umemonitor.asp

Alexander

"Paul Steele" <pa*********@ac adiau.ca> wrote in message
news:uA******** ******@TK2MSFTN GP12.phx.gbl...
I am writing a C# app that needs to periodically poll for cdroms and usb
storage device insertions. I've looked at the WMI functions but haven't
found anything all that useful. The closest is Win32_DiskDrive , but it
doesn't seem to return any information on cdrom devices. I suspect there
might be a Win32 API call, but I haven't found any info yet using Google.
Is there a way to achieve this in C#?


Nov 16 '05 #4
Read the comments at the bottom.

"Paul Steele" <pa*********@ac adiau.ca> wrote in message
news:en******** ********@TK2MSF TNGP10.phx.gbl. ..
This is definitely a good starting point. Unfortunately it does not detect
USB key insertions...


Nov 16 '05 #5
I presume you are referring to the comment:

"The first one is dbcv_flags. This field will tell us the nature of the
volume that was mounted (or dismounted). It can be either a media volume
like a CD (the flag will have a DBTF_MEDIA flag) or a network share
(DBTF_NET). In this case we will only be interested in filtering the
DBTF_MEDIA value. The other field is dbcv_unitmask, which is a bit vector
that tells us which drive letters were mounted."

If I remove the check for DBTF_MEDIA in the code, then it does detect USB
keys. Unfortunately it also detects network share mounts. There doesn't seem
to be a differentiation between a USB Key and network media. Am I
overlooking something?

"Alexander Shirshov" <al*******@omni talented.com> wrote in message
news:e9******** ******@TK2MSFTN GP09.phx.gbl...
Read the comments at the bottom.

"Paul Steele" <pa*********@ac adiau.ca> wrote in message
news:en******** ********@TK2MSF TNGP10.phx.gbl. ..
This is definitely a good starting point. Unfortunately it does not
detect USB key insertions...

Nov 16 '05 #6

"Paul Steele" <pa*********@ac adiau.ca> wrote in message
news:uA******** ******@TK2MSFTN GP12.phx.gbl...
I am writing a C# app that needs to periodically poll for cdroms and usb
storage device insertions. I've looked at the WMI functions but haven't
found anything all that useful. The closest is Win32_DiskDrive , but it
doesn't seem to return any information on cdrom devices. I suspect there
might be a Win32 API call, but I haven't found any info yet using Google.
Is there a way to achieve this in C#?


Use 'Win32_LogicalD isk' instead of Win32_DiskDrive and register a
asynchronous event handler for __InstanceModif icationEvent, something like
this will do.

using System.Manageme nt;
class TestClass{
public static void Main() {
TestClasswe = new TestClass();
ManagementEvent Watcher w= null;
WqlEventQuery q = new WqlEventQuery() ;
ManagementScope scope = new ManagementScope ("root\\CIMV2") ;
try {
q.EventClassNam e = "__InstanceModi ficationEvent";
q.WithinInterva l = new TimeSpan(0,0,3) ;
// DriveType - 5: CDROM
q.Condition = @"TargetInstanc e ISA 'Win32_LogicalD isk' and
TargetInstance. DriveType = 5 and TargetInstance. VolumeName != null";
w = new ManagementEvent Watcher(scope, q);
// register async. event handler
w.EventArrived += new EventArrivedEve ntHandler(we.CD REventArrived);
w.Start();
// Do something usefull,block thread for testing
Console.ReadLin e();
}
catch(Exception e) {
Console.WriteLi ne(e.Message);
}
finally {
w.Stop();
}
}
// Dump some properties
public void CDREventArrived (object sender, EventArrivedEve ntArgs e) {
//Get the Event object and display it
PropertyData pd;
if(( pd = e.NewEvent.Prop erties["TargetInstance "]) != null)
{
ManagementBaseO bject mbo = pd.Value as ManagementBaseO bject;
Console.WriteLi ne(mbo.Properti es["VolumeName "].Value);
}

Willy.
Nov 16 '05 #7
I put in your code more or less as given but the event never fires. I'm not
familiar with ManagementEvent Watcher, which makes the code somewhat vague,
although I get the general idea behind it. Is there something I can do to
test it?

"Willy Denoyette [MVP]" <wi************ *@pandora.be> wrote in message
news:uY******** ******@TK2MSFTN GP09.phx.gbl...

"Paul Steele" <pa*********@ac adiau.ca> wrote in message
news:uA******** ******@TK2MSFTN GP12.phx.gbl...
I am writing a C# app that needs to periodically poll for cdroms and usb
storage device insertions. I've looked at the WMI functions but haven't
found anything all that useful. The closest is Win32_DiskDrive , but it
doesn't seem to return any information on cdrom devices. I suspect there
might be a Win32 API call, but I haven't found any info yet using Google.
Is there a way to achieve this in C#?


Use 'Win32_LogicalD isk' instead of Win32_DiskDrive and register a
asynchronous event handler for __InstanceModif icationEvent, something like
this will do.

using System.Manageme nt;
class TestClass{
public static void Main() {
TestClasswe = new TestClass();
ManagementEvent Watcher w= null;
WqlEventQuery q = new WqlEventQuery() ;
ManagementScope scope = new ManagementScope ("root\\CIMV2") ;
try {
q.EventClassNam e = "__InstanceModi ficationEvent";
q.WithinInterva l = new TimeSpan(0,0,3) ;
// DriveType - 5: CDROM
q.Condition = @"TargetInstanc e ISA 'Win32_LogicalD isk' and
TargetInstance. DriveType = 5 and TargetInstance. VolumeName != null";
w = new ManagementEvent Watcher(scope, q);
// register async. event handler
w.EventArrived += new EventArrivedEve ntHandler(we.CD REventArrived);
w.Start();
// Do something usefull,block thread for testing
Console.ReadLin e();
}
catch(Exception e) {
Console.WriteLi ne(e.Message);
}
finally {
w.Stop();
}
}
// Dump some properties
public void CDREventArrived (object sender, EventArrivedEve ntArgs e) {
//Get the Event object and display it
PropertyData pd;
if(( pd = e.NewEvent.Prop erties["TargetInstance "]) != null)
{
ManagementBaseO bject mbo = pd.Value as ManagementBaseO bject;
Console.WriteLi ne(mbo.Properti es["VolumeName "].Value);
}

Willy.

Nov 16 '05 #8

"Paul Steele" <pa*********@ac adiau.ca> wrote in message
news:eh******** ******@tk2msftn gp13.phx.gbl...

"Willy Denoyette [MVP]" <wi************ *@pandora.be> wrote in message
news:OG******** ******@TK2MSFTN GP12.phx.gbl...

"Paul Steele" <pa*********@ac adiau.ca> wrote in message
news:O4******** ******@TK2MSFTN GP14.phx.gbl...
I put in your code more or less as given but the event never fires. I'm
not familiar with ManagementEvent Watcher, which makes the code somewhat
vague, although I get the general idea behind it. Is there something I
can do to test it?


Change the query string into:
q.Condition = @"TargetInstanc e ISA 'Win32_LogicalD isk' and
TargetInstance. DriveType = 5";
, and insert and/or remove the CD into/from the drive.
With this change all modifications to to 'Win32_LogicalD isk' will fire
an event, while the original query will only fire when a named volume is
inserted.


Found the problem. I didn't notice that "finally" clause in the try/catch
was executing. I has removed the readline because I moved to code to a
button. Stupid mistake and the program does seem to work. There is one
weird side effect. On my desktop a floppy seek occurs every 3 seconds,
probably because the event requires the OS to query all logical devices,
including the floppy. It's too bad it can't make a silent check for the
floppy...


You can prevent this by including the DeviceId in the query.

q.Condition = @"TargetInstanc e ISA 'Win32_LogicalD isk' and
TargetInstance. DriveType = 5 and TargetInstance. DeviceId='E:'" // where E:
is the drive letter of the CD drive

Willy.


Nov 16 '05 #9
rhr
1 New Member
Willy,
Great work, it works perfect in console app.

However do you have any idea as to why your code is not working in a Windows app?
Also after using it in console app, my A: drive keeps checking for a floppy almost every 5 secs. Do you know what is causing that? In Windows Task Manager I have a CDDetector.csho st.exe that I am not able to end the process of, do you think this is what causing the A: drive issue?

Great job though:)

Thanks.
May 4 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2812
by: Damon Morbius | last post by:
Is there a standard way to detect the device a visitor is using to access your site (i.e. Cell phone, handheld, web browser). Ultimately my goal is to detect what kind of device a visitor is using at a domain level(www.domain.com) then send them to the appropriate url (www.domain.com/wap, www.domain.com/palm). Any help is greatly appreciated. Thanks in advance.
3
2608
by: M | last post by:
I searched the FAQ for this NG and found no answers to my question... I'm writing an application in Java (I'm not a C programmer), however I need to be able to detect WHICH drive (d:\, e:\ etc...) on a win2k machine the CDROM drive is on. I assume that C or C++ can do this. The C/C++ code will then be wrapped in a JNI layer to be used by the java code. Basically, all I want the C code to do is return a letter corresponding to the...
8
13656
by: Hayato Iriumi | last post by:
Hello, I'm trying to find a way to detect whether CD-ROM was inserted into the CD-ROM drive using C#. Does anyone have any idea how to do this? WMI? Win32 API? TIA
6
24560
by: sanjana | last post by:
hi i wanna detect if a anything is connected to the usb port I am using system.management class for tht purpose this is my code class usbdetect { public static void Main() { usbdetect we = new usbdetect();
3
9080
by: Ognjen Bezanov | last post by:
Hello, I am trying to control a CD-ROM drive using python. The code I use is shown below.
4
3275
by: pankajprakash | last post by:
Hi, i have a windows application in vb.net. I just want to detect the USB pen port whether is it connected or not, if connected then i want to copy and remove the file from the pen derive.
0
1174
Ali Rizwan
by: Ali Rizwan | last post by:
hello everybody I am making an interactive software for a company, but the problem is that how can we detect the cdrom because all the data is stored in CD. Suppose there are to CD Roms in a pc how the software detect in which rom the Cd is wher the data is. Plz Help me or i will lost my task.
1
1624
Ali Rizwan
by: Ali Rizwan | last post by:
How to print a flexgrid instead of whole form How to set print quality How to detect CDROM, that is the required cd is inserted or not
3
26743
by: Charming12 | last post by:
Hi All, I have to deal with some devices like Pen Tablet, WebCam etc to work for a product. Now my Problem is some times while working , I am not able to tell whether a certain device is connected to PC . So , Is there any way in C# where i can detect if device is connected using USB port or serial port. Any help will be useful. Thanks in Advance Eric.
0
9961
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9800
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10438
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9597
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7148
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5817
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6014
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4642
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4243
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.