C# Code 4 USB

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO.IsolatedStorage;
using System.IO.Compression;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace WindowsApplication1
{

public partial class Form1 : Form
{

public Form1()
{
InitializeComponent();

}

/*private class SP_DEVINFO_DATA
{
public int cbSize;
public Guid ClassGuid;
public int DevInst; // DEVINST handle
public ulong Reserved;
};*/
/*[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);
*/

private class Sp_DEVICE_INTERFACE_DETAIL_DATA
{
public int cbsize;
public string Devicepath;
}

private class SP_DEVICE_INTERFACE_DATA
{
public int cbSize;
public Guid InterfaceClassGuid;
public int FLAGS;
public int Reserved;
};

//Step1: Obtaining the Device Interface Guid
[DllImport("hid.dll")]
private static extern void HidD_GetHidGuid(ref Guid GUID);
//end step1: Obtaining the Device Interface Guid

//Step 2: requesting a pointer to a device Information Set
[DllImport("setupapi.dll",CharSet=CharSet.Auto)]
private static extern IntPtr SetupDiGetClassDevsA(ref Guid ClassGuid, UInt32 Enumerator,IntPtr hwndParent, UInt32 Flags);
IntPtr deviceinfoset;
//End Step 2: requesting a pointer to a device Information Set

//Step3: Identifying a Device Interface
[DllImport("setupapi.dll")]
private static extern Boolean SetupDiEnumDeviceInterfaces(IntPtr DeviceInfoSet, int DeviceInfoData, ref Guid InterfaceClassGuid, int MemberIndex, ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData);
SP_DEVICE_INTERFACE_DATA MyDeviceInterfaceData = new SP_DEVICE_INTERFACE_DATA();
int MemberIndex;
Boolean Result;
//End Step3: Identifying a Device Interface

//Step4: requesting a structure containing the Device Path Name
[DllImport("setupapi.dll", CharSet = CharSet.Auto)]
private static extern Boolean SetupDiGetDeviceInterfaceDetail(IntPtr DeviceInfoSet, ref SP_DEVICE_INTERFACE_DATA DeviceIntefaceData, IntPtr DeviceInterfaceDetailData, int DeviceInterfacedetailDatasize, ref int DeviceInterfacedetaildataSize, IntPtr DeviceInfoData);
int BufferSize;
Boolean Success;
int counter;
//End Step4: requesting a structure containing the Device Path Name

/*[DllImport("setupapi.dll")]
private static extern Boolean SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet, UInt32 MemberIndex,SP_DEVINFO_DATA DeviceInfoData);
*/

private void Form1_Load(object sender, EventArgs e)
{
counter = 0;
//Form Load code
//Step1: code to call step1(Obtaining the Device Interface Guid)(GUID: Globally Unique identifier)

Guid HidGuid = new Guid();
HidD_GetHidGuid(ref HidGuid);
//End Step1: code to call step1(Obtaining the Device Interface Guid)(GUID: Globally Unique identifier)

//Step2: code to call step2(Identifying a device interface)(A call to SetupDiEnumdevicesInterface retrieves a pointer to a structure that identifies a specific device interface in the previously retrieved Deviceinfoset array)

const int DIGCF_PRESENT = (0×00000002);

//const int DIGCF_DEVICEINTERFACE = (0×00000001);
deviceinfoset = SetupDiGetClassDevsA(ref HidGuid, 0, IntPtr.Zero, DIGCF_PRESENT);
//Display
label1.Text = “Device Info Set = ” + deviceinfoset.ToString();
label2.Text = “HidGuid = ” + HidGuid.ToString();
//End dispaly
//End Step2: code to call step2

//Step3: Identifying a Device Interface
MyDeviceInterfaceData.cbSize = 28;
MyDeviceInterfaceData.InterfaceClassGuid = System.Guid.Empty;
MyDeviceInterfaceData.FLAGS = 0;
MyDeviceInterfaceData.Reserved = 0;
MemberIndex=0;
Result=SetupDiEnumDeviceInterfaces(deviceinfoset,0,ref HidGuid,MemberIndex,ref MyDeviceInterfaceData);
//Display
label3.Text = “Result = ” + Result.ToString();
//End Display
//End Step3: Identifying a Device Interface

//Step4: requesting a structure containing the Device Path Name
Success = SetupDiGetDeviceInterfaceDetail(deviceinfoset, ref MyDeviceInterfaceData, IntPtr.Zero, 0, ref BufferSize, IntPtr.Zero);
MessageBox.Show(“success = ” + Success.ToString(),”USB Alert!!!!”);
IntPtr detailDataBuffer;
detailDataBuffer = Marshal.AllocHGlobal(BufferSize);
Marshal.WriteInt32(detailDataBuffer, 4 + Marshal.SystemDefaultCharSize);
Success = SetupDiGetDeviceInterfaceDetail(deviceinfoset, ref MyDeviceInterfaceData, detailDataBuffer, BufferSize, ref BufferSize, IntPtr.Zero);
MessageBox.Show(“New success = ” + Success.ToString(), “USB Alert!!!!”);
//Display
label4.Text = “New success = ” + Success.ToString();
//End Display
//End Step4: requesting a structure containing the Device Path Name

//step5: Extracting the Device Path Name
string Devicepathname;
IntPtr pDevicePathName;
pDevicePathName = new IntPtr(detailDataBuffer.ToInt32() + 4);
Devicepathname = Marshal.PtrToStringAuto(pDevicePathName);
Marshal.FreeHGlobal(detailDataBuffer);
//display
label5.Text = “path name = ” + pDevicePathName.ToString();
label6.Text = “device path name = ” + Devicepathname;

MessageBox.Show(“path name = ” + pDevicePathName.ToString(), “USB Alert!!!!”);
MessageBox.Show(“device path name = ” + Devicepathname, “USB Alert!!!!”);
label7.Text = “File Exists = ” + File.Exists(Devicepathname).ToString();
//End Display

//End step5: Extracting the Device Path Name
//End Form Load code
timer1.Interval = 200;
timer1.Start();

//label3.Text = Success.ToString();
//MessageBox.Show(“Hello”);

/*FileVersionInfo fversinfo;
FileInfo finfo;
string filepath;
filepath = “F:/abc.pqr”;
if (File.Exists(filepath))
{
//get version information
fversinfo = FileVersionInfo.GetVersionInfo(filepath);

//print file description
label1.Text = fversinfo.FileDescription;

//print full path to file
label2.Text = “fullpath : {0}” + fversinfo.FileName;
//print major.minor version info
label3.Text = “version : {0}.{1}” + fversinfo.FileMajorPart + fversinfo.FileMinorPart;

//cleanup
fversinfo = null;

//get general file info
finfo = new FileInfo(filepath);

//get file attributes
label4.Text = “attributes: {0}” + finfo.Attributes.ToString();

//get the size of the file
label5.Text = “file size : {0}k” + finfo.Length / 1024;

//get the last time the file was written to
label6.Text = “last write: {0}” + finfo.LastWriteTime.ToShortDateString();
//cleanup
finfo = null;
}
else
{
//MessageBox.Show(“File not found”);
label7.Text = “File not found”;
}*/

}

private void timer1_Tick(object sender, EventArgs e)
{
//Form Load code
//Step1: code to call step1
Guid HidGuid = new Guid();
HidD_GetHidGuid(ref HidGuid);
//End Step1: code to call step1

//Step2: code to call step2
const int DIGCF_PRESENT = 0×054C;
//const int DIGCF_DEVICEINTERFACE = (0×00000001);
deviceinfoset = SetupDiGetClassDevsA(ref HidGuid, 0, IntPtr.Zero, DIGCF_PRESENT);
//Display
label1.Text = “Device Info Set = ” + deviceinfoset.ToString();
label2.Text = “HidGuid = ” + HidGuid.ToString();
//End dispaly
//End Step2: code to call step2

//Step3: Identifying a Device Interface
MyDeviceInterfaceData.cbSize = 28;
MyDeviceInterfaceData.InterfaceClassGuid = System.Guid.Empty;
MyDeviceInterfaceData.FLAGS = 0;
MyDeviceInterfaceData.Reserved = 0;
MemberIndex = 0;
Result = SetupDiEnumDeviceInterfaces(deviceinfoset, 0, ref HidGuid, MemberIndex, ref MyDeviceInterfaceData);
//Display
label3.Text = “Result = ” + Result.ToString();
//End Display
//End Step3: Identifying a Device Interface

//Step4: requesting a structure containing the Device Path Name
Success = SetupDiGetDeviceInterfaceDetail(deviceinfoset, ref MyDeviceInterfaceData, IntPtr.Zero, 0, ref BufferSize, IntPtr.Zero);
//MessageBox.Show(“success = ” + Success.ToString());
IntPtr detailDataBuffer;
detailDataBuffer = Marshal.AllocHGlobal(BufferSize);
Marshal.WriteInt32(detailDataBuffer, 4 + Marshal.SystemDefaultCharSize);
Success = SetupDiGetDeviceInterfaceDetail(deviceinfoset, ref MyDeviceInterfaceData, detailDataBuffer, BufferSize, ref BufferSize, IntPtr.Zero);
//MessageBox.Show(“New success = ” + Success.ToString());
//Display
label4.Text = “New success = ” + Success.ToString();
//End Display
//End Step4: requesting a structure containing the Device Path Name

//step5: Extracting the Device Path Name
string Devicepathname;
IntPtr pDevicePathName;
pDevicePathName = new IntPtr(detailDataBuffer.ToInt32() + 4);
Devicepathname = Marshal.PtrToStringAuto(pDevicePathName);
Marshal.FreeHGlobal(detailDataBuffer);
//display
label5.Text = “path name = ” + pDevicePathName.ToString();
label6.Text = “device path name = ” + Devicepathname;
label7.Text = “File Exists = ” + File.Exists(Marshal.PtrToStringAuto(pDevicePathName)).ToString();
counter=counter + 1;
label8.Text = “Counter : ” + counter.ToString();
//MessageBox.Show(“path name = ” + pDevicePathName.ToString());
//MessageBox.Show(“device path name = ” + Devicepathname);
//End Display

//End step5: Extracting the Device Path Name
//End Form Load code

}

private void button1_Click(object sender, EventArgs e)
{
timer1.Stop();
button1.Enabled = false;
}
}
}

9 Responses to this post.

  1. Posted by pejman on August 15, 2007 at 9:56 am

    it is very very helpfull.

    Reply

  2. Posted by kamesh on January 4, 2008 at 8:57 am

    This is raising an error Like Type Not Defined Like ths

    An unhandled exception of type ‘System.Runtime.InteropServices.MarshalDirectiveException’ occurred in WindowsApplication1.exe

    Additional information: Can not marshal parameter #2: The type definition of this type has no layout information.

    Reply

  3. Posted by Jeroen on February 25, 2008 at 7:55 am

    Hello,

    I like the code, and I think it will help me achieve what I need to do.
    But when I try to run it is get the following exception:
    System.Security.SecurityException was unhandled

    I don’t know Why I get this exception and I don’t know how to resolve it.
    I have created a form with all the labels/button/timer.

    can you please help me?

    Jeroen

    Reply

  4. Posted by Jeroen on February 25, 2008 at 8:10 am

    Sorry one more comment:

    the error is thrown at:
    HidD_GetHidGuid(ref HidGuid);
    in the Form1_Load function

    Reply

  5. Posted by duc on March 21, 2008 at 2:35 am

    It seems that the code above uses .net 2.0. Can anyone have the same code for .net 1.1?

    Reply

  6. Nice Article and very helpful also

    Reply

  7. Posted by Maverick on June 14, 2008 at 11:32 pm

    Could anyone help me?
    When I create window app project in VC#.net 2005 then I replace all its auto generate code with this code but found 142 error about expected ; or ” or ).
    How I can use this code properly?

    Thank you.^^’

    Reply

  8. Posted by Maverick on June 15, 2008 at 12:35 am

    OK! I compiled without error.
    But It show message box “success = fail”.
    I try to plug a DELL usb keyboard on my PC then run program again but has the same result as above. Anyone share with me please.
    thanks so much^^

    Reply

  9. Posted by sumant on February 28, 2009 at 9:27 am

    Thank U

    Reply

Respond to this post