Click here to Skip to main content
15,885,985 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi there!

I am working on a project in which there is a module about detection of usb insertion or removal.

I am stuck guys. Please help me to sort out this problem.

Regards!!!
Posted
Updated 14-Jul-10 10:59am
v2
Comments
Sandeep Mewara 14-Jul-10 17:00pm    
Where are you stuck? Issue?
BTW, similar question has been asked off late... just use the CP search and you should get how to detect insertion/removal of a USB.
a.w.a.i.s 14-Jul-10 17:02pm    
wht is cp???...:D
a.w.a.i.s 14-Jul-10 17:04pm    
i have tried code at this page...:
http://www.techtalkz.com/c-c-sharp/182048-need-detect-insertion-removal-usb-drive.html

it works fine for Console...but how to use it in Form application...
plz help...m new in c#...
DaveyM69 14-Jul-10 18:34pm    
There is no difference in code between WinForms and Console with the following exceptions...
Move the code out of the Main method and put it in it's own new (normally not static) method with a suitable name and call that at a suitable point (after the main form's constructor has done it's thing).
Console.Write/WriteLine will write to the VS output window (View|Output) instead of a console window.
Christian Graus 14-Jul-10 19:29pm    
What is CP ? Are you dense ? Code Project.

1 solution

namespace DeviceEnumerator
{
	using System;
	using System.Runtime.InteropServices;

	public class SetupAPI
	{
		[DllImport("hid.dll", SetLastError=true)]
		public static extern  unsafe void  HidD_GetHidGuid(
			ref Guid lpHidGuid
			);

		 
		[DllImport("setupapi.dll", SetLastError=true)]
		public static extern  unsafe int SetupDiGetClassDevs(
			ref Guid  lpGuid,
			int*	  Enumerator,
			int*      hwndParent,
			ClassDevsFlags  Flags
			);

		[DllImport("setupapi.dll", SetLastError=true)]
		public static extern  unsafe int SetupDiGetClassDevs(
			int*  guid,
			int*  Enumerator,
			int*  hwndParent,
			ClassDevsFlags  Flags
			);

		[StructLayout(LayoutKind.Sequential)]
		public struct SP_DEVINFO_DATA
		{
			public int  cbSize;
			public Guid ClassGuid;
			public int  DevInst;
			public int  Reserved;
		}


		[DllImport("setupapi.dll", SetLastError=true)]
		public static extern unsafe int SetupDiEnumDeviceInfo(
			int  DeviceInfoSet,
			int	 Index, 
			ref  SP_DEVINFO_DATA DeviceInfoData
			);


		[Flags]
			public enum ClassDevsFlags
		{
			DIGCF_DEFAULT			= 0x00000001,
			DIGCF_PRESENT			= 0x00000002,
			DIGCF_ALLCLASSES		= 0x00000004,
			DIGCF_PROFILE			= 0x00000008,
			DIGCF_DEVICEINTERFACE	= 0x00000010,
		}

		// Device interface data
		[StructLayout(LayoutKind.Sequential)]
			public unsafe struct SP_DEVICE_INTERFACE_DATA 
		{
			public int cbSize;
			public Guid InterfaceClassGuid;
			public int Flags;
			public int Reserved;
		}

		// Device interface detail data
		[StructLayout(LayoutKind.Sequential, CharSet= CharSet.Ansi)]
		public unsafe struct PSP_DEVICE_INTERFACE_DETAIL_DATA
		{
			public int  cbSize;
			[MarshalAs(UnmanagedType.ByValTStr, SizeConst= 256)]
			public string DevicePath;
		}


		[DllImport("setupapi.dll", SetLastError=true)]
		public static extern  unsafe int SetupDiEnumDeviceInterfaces(
			int  DeviceInfoSet,
			int  DeviceInfoData,
			ref  Guid  lpHidGuid,
			int  MemberIndex,
			ref  SP_DEVICE_INTERFACE_DATA lpDeviceInterfaceData);


		[DllImport("setupapi.dll", SetLastError=true)]
		public static extern  unsafe int SetupDiGetDeviceInterfaceDetail(
			int  DeviceInfoSet,
			ref SP_DEVICE_INTERFACE_DATA lpDeviceInterfaceData,
			int* aPtr,
			int detailSize,
			ref int requiredSize,
			int* bPtr);

		[DllImport("setupapi.dll", SetLastError=true)]
		public static extern  unsafe int SetupDiGetDeviceInterfaceDetail(
			int  DeviceInfoSet,
			ref SP_DEVICE_INTERFACE_DATA lpDeviceInterfaceData,
			ref PSP_DEVICE_INTERFACE_DETAIL_DATA myPSP_DEVICE_INTERFACE_DETAIL_DATA,
			int detailSize,
			ref int requiredSize,
			int* bPtr);

		public enum RegPropertyType
		{
			SPDRP_DEVICEDESC                  = 0x00000000, // DeviceDesc (R/W)
			SPDRP_HARDWAREID                  = 0x00000001, // HardwareID (R/W)
			SPDRP_COMPATIBLEIDS               = 0x00000002, // CompatibleIDs (R/W)
			SPDRP_UNUSED0                     = 0x00000003, // unused
			SPDRP_SERVICE                     = 0x00000004, // Service (R/W)
			SPDRP_UNUSED1                     = 0x00000005, // unused
			SPDRP_UNUSED2                     = 0x00000006, // unused
			SPDRP_CLASS                       = 0x00000007, // Class (R--tied to ClassGUID)
			SPDRP_CLASSGUID                   = 0x00000008, // ClassGUID (R/W)
			SPDRP_DRIVER                      = 0x00000009, // Driver (R/W)
			SPDRP_CONFIGFLAGS                 = 0x0000000A, // ConfigFlags (R/W)
			SPDRP_MFG                         = 0x0000000B, // Mfg (R/W)
			SPDRP_FRIENDLYNAME                = 0x0000000C, // FriendlyName (R/W)
			SPDRP_LOCATION_INFORMATION        = 0x0000000D ,// LocationInformation (R/W)
			SPDRP_PHYSICAL_DEVICE_OBJECT_NAME = 0x0000000E, // PhysicalDeviceObjectName (R)
			SPDRP_CAPABILITIES                = 0x0000000F, // Capabilities (R)
			SPDRP_UI_NUMBER                   = 0x00000010, // UiNumber (R)
			SPDRP_UPPERFILTERS                = 0x00000011, // UpperFilters (R/W)
			SPDRP_LOWERFILTERS                = 0x00000012, // LowerFilters (R/W)
			SPDRP_BUSTYPEGUID                 = 0x00000013, // BusTypeGUID (R)
			SPDRP_LEGACYBUSTYPE               = 0x00000014, // LegacyBusType (R)
			SPDRP_BUSNUMBER                   = 0x00000015, // BusNumber (R)
			SPDRP_ENUMERATOR_NAME             = 0x00000016, // Enumerator Name (R)
			SPDRP_SECURITY                    = 0x00000017, // Security (R/W, binary form)
			SPDRP_SECURITY_SDS                = 0x00000018, // Security (W, SDS form)
			SPDRP_DEVTYPE                     = 0x00000019, // Device Type (R/W)
			SPDRP_EXCLUSIVE                   = 0x0000001A, // Device is exclusive-access (R/W)
			SPDRP_CHARACTERISTICS             = 0x0000001B, // Device Characteristics (R/W)
			SPDRP_ADDRESS                     = 0x0000001C, // Device Address (R)
			SPDRP_UI_NUMBER_DESC_FORMAT       = 0x0000001E, // UiNumberDescFormat (R/W)
			SPDRP_MAXIMUM_PROPERTY            = 0x0000001F  // Upper bound on ordinals
		}

		[DllImport("setupapi.dll", SetLastError=true)]
		public  static extern unsafe int SetupDiGetDeviceRegistryProperty(
			int					DeviceInfoSet,
			ref SP_DEVINFO_DATA DeviceInfoData,
			RegPropertyType		Property, 
			int*				PropertyRegDataType, 
			int*				PropertyBuffer, 
			int					PropertyBufferSize, 
			ref int				RequiredSize
		);

		// Device interface detail data
		[StructLayout(LayoutKind.Sequential, CharSet= CharSet.Ansi)]
		public unsafe struct DATA_BUFFER
		{
			[MarshalAs(UnmanagedType.ByValTStr, SizeConst= 1024)]
			public string Buffer;
		}

		[DllImport("setupapi.dll", SetLastError=true)]
		public  static extern unsafe int SetupDiGetDeviceRegistryProperty(
			int					DeviceInfoSet,
			ref SP_DEVINFO_DATA DeviceInfoData,
			RegPropertyType		Property, 
			int*				PropertyRegDataType, 
			ref DATA_BUFFER		PropertyBuffer, 
			int					PropertyBufferSize, 
			ref int				RequiredSize
		);

	}
}


//main class

using System;
using System.Runtime.InteropServices;

namespace DeviceEnumerator
{
	class Class1
	{
		[STAThread]
		static unsafe void Main(string[] args)
		{
			//	DisplayGuid : TGUID = '{4d36e968-e325-11ce-bfc1-08002be10318}';
			//	HidGuid     : TGUID = '{745a17a0-74d3-11d0-b6fe-00a0c90f57da}';
			//	USBGuid     : TGUID = '{36FC9E60-C465-11CF-8056-444553540000}';

			Guid guid = new Guid("{36FC9E60-C465-11CF-8056-444553540000}");

			int PnPHandle = SetupAPI.SetupDiGetClassDevs(
				ref guid,
				null, 
				null,
				SetupAPI.ClassDevsFlags.DIGCF_PRESENT
			);

			int	result		= -1;
			int DeviceIndex = 0;

			while (result != 0)
			{
				SetupAPI.SP_DEVINFO_DATA DeviceInfoData = new SetupAPI.SP_DEVINFO_DATA();
				DeviceInfoData.cbSize = Marshal.SizeOf(DeviceInfoData);
				result = SetupAPI.SetupDiEnumDeviceInfo(PnPHandle, DeviceIndex, ref DeviceInfoData);

				if (result == 1)
				{
					Console.WriteLine("{0}:\n\t{1}\n\t{2}\n\t{3}\n\t{4}", 
						GetRegistryProperty(PnPHandle, ref DeviceInfoData, SetupAPI.RegPropertyType.SPDRP_DEVICEDESC),
						GetRegistryProperty(PnPHandle, ref DeviceInfoData, SetupAPI.RegPropertyType.SPDRP_CLASS		),
						GetRegistryProperty(PnPHandle, ref DeviceInfoData, SetupAPI.RegPropertyType.SPDRP_CLASSGUID	),
						GetRegistryProperty(PnPHandle, ref DeviceInfoData, SetupAPI.RegPropertyType.SPDRP_DRIVER	),
						GetRegistryProperty(PnPHandle, ref DeviceInfoData, SetupAPI.RegPropertyType.SPDRP_MFG		)
						
					);
				}

				DeviceIndex++;
			}

			Console.ReadLine();
		}

		public unsafe static string GetRegistryProperty(int PnPHandle, ref SetupAPI.SP_DEVINFO_DATA DeviceInfoData, SetupAPI.RegPropertyType Property)
		{
			int RequiredSize = 0;
			SetupAPI.DATA_BUFFER Buffer = new SetupAPI.DATA_BUFFER();

			int result = SetupAPI.SetupDiGetDeviceRegistryProperty(
				PnPHandle,
				ref DeviceInfoData,
				Property,
				null, 
				ref Buffer,
				1024,
				ref RequiredSize
				);

			return	Buffer.Buffer;

		}
	}
}
 
Share this answer
 
Comments
John Harries 18-Jun-11 0:57am    
Why 'result' inside 'static unsafe void Main(string[] args)' always 0? I use a Microsoft USB HID keyboard but it was undetected. Can anyone help me?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900