TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Detect insertion and removal of SDCard C#
Sagar Pardeshi
Jun 20
2014
Code
10.7
k
0
0
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
expand
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Management;
using
System.Text;
using
System.Threading.Tasks;
namespace
WTTestSDCard
{
class
Program
{
public
static
void
Main()
{
addInsetSDCard();
AddremovalSD();
for
(; ; ) ;
}
public
static
void
addInsetSDCard()
{
ManagementEventWatcher objCardWatcher =
null
;
objCardWatcher = GetWatcher(
"__InstanceOperationEvent"
,
"TargetInstance ISA 'Win32_PhysicalMedia' and TargetInstance.MediaType=30"
);
objCardWatcher.EventArrived +=
new
EventArrivedEventHandler(CardEventRaised);
//subscribes to an event based on event query
objCardWatcher.Start();
}
public
static
void
AddremovalSD()
{
ManagementEventWatcher objCardWatcher =
null
;
objCardWatcher = GetWatcher(
"__InstanceOperationEvent"
,
"TargetInstance ISA 'Win32_CDROMDrive' and TargetInstance.MediaType=30"
)
;
objCardWatcher.EventArrived +=
new
EventArrivedEventHandler(CardEventpassed);
//subscribes to an event based on event query
objCardWatcher.Start();
}
public
static
ManagementEventWatcher GetWatcher(
string
WatcherType,
string
strQuery)
{
string
objWatcherType = WatcherType;
//queries for events occuring at SDCard Port
WqlEventQuery objWqlEventQuery =
new
WqlEventQuery(objWatcherType,
new
TimeSpan(0, 0, 3), strQuery);
// Bind to local machine
ManagementScope objScope =
new
ManagementScope(
"root\\CIMV2"
);
objScope.Options.EnablePrivileges =
true
;
ManagementEventWatcher objEventWatcher =
new
ManagementEventWatcher(objScope, objWqlEventQuery);
return
objEventWatcher;
}
public
static
void
CardEventRaised(
object
sender, EventArrivedEventArgs e)
{
try
{
Console.WriteLine(
"CARD EVENT IS inserted raised"
);
}
catch
(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public
static
void
CardEventpassed(
object
sender, EventArrivedEventArgs e)
{
try
{
Console.WriteLine(
"Card EVENT IS Removed raised"
);
}
catch
(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}