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);
}
}
}
}How to detect insertion and removal of SDCard C#
