Hi I want to do something when a memory stick attached to PC. Now I use a timer and check it in every tick whether any memory stick is plugged(use DriveInfo or with querying WMI) Is there any event driven model available to do? for example i use an event in my program that raise whenever a memory stick is plugged in to computer?
Asked
Active
Viewed 168 times
1
-
@dr_csharp: What is ***sth***? – KMån Oct 05 '10 at 12:41
-
@KMan, `s` is a variable and `s`-th is an ordinal number. – avakar Oct 05 '10 at 12:41
-
@Avakar: Shouldn't it be *n* th? – KMån Oct 05 '10 at 12:50
-
2Then please write "something" – H H Oct 05 '10 at 14:18
-
@KMan: "sth" is Nerd for "I'm a dork with no social interaction skills" – John Dibling Oct 05 '10 at 14:47
-
@John: Or "my time is so extremely valuable that saving a dozen keypresses for *me* is worth no amount of wasted time for *you* trying to decipher my question". – jalf Oct 05 '10 at 16:20
-
This [answer](http://stackoverflow.com/questions/715739/looking-for-c-code-for-detecting-removable-drive-usb-flash) might help. – KMån Oct 05 '10 at 12:46
1 Answers
1
You want to handle the WM_DEVICECHANGE message in your wndproc. When you handle that, you can also call RegisterDeviceNotification to get notification that the stick is being cleanly ejected.
When you recieve a WM_DEVICECHANGE, you want to check the wParam - DBT_DEVICEARRIVAL (0x800) is what you're looking for.
In C++, you should have no trouble with the wndproc. In c#, you'll want to override your main form's WndProc method and check m.Msg == 0x219 and m.WParam == 0x800. Note that not ALL of these will be a memory stick - but you can use this to notify you to check for drive insertion rather than a timer.
Philip Rieck
- 32,368
- 11
- 87
- 99
-
I don't know why when i do this, as I plug memory stick to PC, it raises more than 3 times ! following code is in C# : if (m.Msg == 0x219 && m.WParam == 0x800) { MessageBox.Show("this is a test"); } – dr_csharp Oct 05 '10 at 13:40
-
It will raise multiple times as the device type is recognized and refined. – Philip Rieck Oct 05 '10 at 13:50
-
This work properly : when m.Msg==0x219 and m.WParam==32768 it means "Plugged In" and when m.WParam=32772 it means "Plugged out" – dr_csharp Oct 05 '10 at 14:01