블로그 이미지
Sunny's

calendar

1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30

Notice

'USB'에 해당되는 글 3

  1. 2011.11.09 Win32_USBHubWMI class USB 정보
  2. 2011.10.27 Enumerate and Auto-Detect USB Drives
  3. 2010.08.25 Windows XP USB로 설치하기4
2011. 11. 9. 09:04 .NET Framework

The Win32_USBHubWMI class represents the management characteristics of a universal serial bus (USB) hub.

The following syntax is simplified from Managed Object Format (MOF) code and includes all of the inherited properties. Properties are listed in alphabetic order, not MOF order.

class Win32_USBHub : CIM_USBHub
{
  uint16   Availability;
  string   Caption;
  uint8    ClassCode;
  uint32   ConfigManagerErrorCode;
  boolean  ConfigManagerUserConfig;
  string   CreationClassName;
  uint8    CurrentAlternateSettings;
  uint8    CurrentConfigValue;
  string   Description;
  string   DeviceID;
  boolean  ErrorCleared;
  string   ErrorDescription;
  boolean  GangSwitched;
  datetime InstallDate;
  uint32   LastErrorCode;
  string   Name;
  uint8    NumberOfConfigs;
  uint8    NumberOfPorts;
  string   PNPDeviceID;
  uint16   PowerManagementCapabilities[];
  boolean  PowerManagementSupported;
  uint8    ProtocolCode;
  string   Status;
  uint16   StatusInfo;
  uint8    SubclassCode;
  string   SystemCreationClassName;
  string   SystemName;
  uint16   USBVersion;
};


아래 Win32 관련 클래스들정보를 참고 할수 있다..
USB 관련 클래스
 Win32_DiskDrive
 Win32_DiskPartition
 Win32_LogicalDisk
 Win32_USBHub

위정보를 통해 USB 관련 정보를 추출 및 제어 가능하다.

출처 : http://msdn.microsoft.com/en-us/library/windows/desktop/aa394506(v=VS.85).aspx

posted by Sunny's
2011. 10. 27. 19:54 .NET Framework


  • Download source - 17.33 KB
  • Download demo - 8.99 KB
  • UsbManager_Demo

    Introduction

    This article describes how to use the .NET System.Management WMI (Windows Management Instrumentation) wrappers to enumerate and describe USB disk drives. It also includes a non-Interop solution for detecting drive state changes as they come online or go offline.

    Contents

    Background

    While writing iTuner, I needed to be able to enumerate USB disk drives (MP3 players) and allow the user to select one with which iTuner could synchronize iTunes playlists. In order to select the correct device, the user needs some basic identifying information beyond just drive letter such as volume name, manufacturer's model name, and available disk space. As an added feature, I wanted the UI to update automatically as USB drives come online or go offline. Finally, I wanted to accomplish this through a tidy, simple interface that did not add tremendous complexity to the main application.

    Caveat: The UsbManager.GetAvailableDisks method can be run in any application type. However, the StateChanged event will not be fired unless running in the context of a WPF or Windows Forms application. This is because the event handler relies on Windows message processing to intercept these state changes as explained below.

    Using the Code

    As an application developer and consumer of this API, you first need an instance of the UsbManager class. This class exposes a very simple interface:

    class UsbManager : IDisposable
    {
        public UsbManager ();
        public event UsbStateChangedEventHandler StateChanged;
        public UsbDiskCollection GetAvailableDisks ();
    }
    
    class UsbDiskCollection : ObservableCollection<UsbDisk>
    {
        public bool Contains (string name);
        public bool Remove (string name);
    }
    
    class UsbDisk
    {
        public ulong FreeSpace { get; }
        public string Model { get; }
        public string Name { get; }
        public ulong Size { get; }
        public string Volume { get; }
        public string ToString ();
    }
    1. Instantiate a new UsbManager using its parameterless constructor.
    2. Wire up an event handler to the StateChanged event.
    3. If desired, call GetAvailableDisks to retrieve a list of current USB disks.

    The UsbDisk class abstracts the information pertaining to a particular USB disk. It includes only the most recognizable fields that a typical end user might use to differentiate drives such as the drive letter (Name), volume name, and manufacturer's model name. It also specifies the available free space and total disk size, both specified in bytes. While other information such as serial numbers, partition or sector data might be of interest to developers, they're quite esoteric to end users.

    That's it! Happy coding! OK, keep reading if you want to understand how it's all put together.

    Inside the Code

    Developing this API was first and foremost an exercise in discovering the WMI classes and their relationships. Unfortunately, WMI does not have a single WMI_USBDiskDrive class with all the properties we want. But the information is there. I started by using the WMI Explorer utility from KS-Soft. It's free and available for download on their Web site.

    A Walk Around the WMI Classes

    The first WMI class that draws your attention is Win32_DiskDrive. Drives are listed with creative and obvious names like "\\PHYSICALDRIVE0". We can filter these by looking at only those with an InterfaceType property value of "USB". Win32_DiskDrive also specifies the Model and Size of the drive. There are lots of other properties, but none are very interesting in this case. Here's the WMI query that retrieves the DeviceID and Model name for USB drives:

    select DeviceID, Model from Win32_DiskDrive where InterfaceType='USB'

    My next stop was the Win32_LogicalDisk class. This gets a bit more interesting right off the bat because instances are listed as drive letters like "C:", "D:", and "S:". We can also fetch the FreeSpace and VolumeName properties. Here's the WMI query:

    select FreeSpace, Size, VolumeName from Win32_LogicalDisk where Name='S:'

    We now need a way to associate Win32_DiskDrive and Win32_LogicalDisk so we can marry these bits of information together. You might think there would be some shared field that allows you join the two classes. No such luck. And that's exactly where the Web came to the rescue and I discovered a bit of code tucked away on MSDN that demonstrates how to associate these classes. We can use the associators operator to discover associations between various classes. Given a Win32_DiskDrive instance, we can use its DeviceID property to determine the Win32_DiskPartition instance associated via Win32_DiskDriveToDiskPartition:

    associators of {Win32_DiskDrive.DeviceID='\\PHYSICALDRIVE1'}
          where AssocClass = Win32_DiskDriveToDiskPartition

    Then using Win32_DiskPartition.DeviceID, we can determine the Win32_LogicalDisk instance associated via Win32_LogicalDiskToPartition:

    associators of {Win32_DiskPartition.DeviceID='Disk #0, Partition #1'}
          where AssocClass = Win32_LogicalDiskToPartition

    Implementing the WMI Queries Using System.Management

    To execute a WMI query, we can use the System.Management.ManagementObjectSearcher class. This class always has the same pattern: search, get, enumerate as shown here:

    ManagementObjectSearcher searcher = 
        new ManagementObjectSearcher("select * from Win32_DiskDrive");
    
    ManagementObjectCollection items = searcher.Get();
    
    foreach (ManagementObject item in items)
    {
    }

    Given the cascading calls needed to query the four WMI classes, we would end up with a fairly ugly nesting of foreach loops. In order to clean this up and make the logic more obvious, I created a simple extension method for the ManagementObjectSearcher class. This extension adds a First() method to the ManagementObjectSearcher class that invokes its Get method, enumerates the resultant collection and immediately returns the first item in that collection:

    public static ManagementObject First (this ManagementObjectSearcher searcher)
    {
        ManagementObject result = null;
        foreach (ManagementObject item in searcher.Get())
        {
            result = item;
            break;
        }
        return result;
    }

    Combine this helper extension with the WMI queries above and we end up with a straightforward code in UsbManager.GetAvailableDisks(). Yes, we still have a nested structure, but testing for null is much more clear than the alternative!

    public UsbDiskCollection GetAvailableDisks ()
    {
        UsbDiskCollection disks = new UsbDiskCollection();
    
        // browse all USB WMI physical disks
        foreach (ManagementObject drive in
            new ManagementObjectSearcher(
                "select DeviceID, Model from Win32_DiskDrive " +
                 "where InterfaceType='USB'").Get())
        {
            // associate physical disks with partitions
            ManagementObject partition = new ManagementObjectSearcher(String.Format(
                "associators of {{Win32_DiskDrive.DeviceID='{0}'}} " +
                      "where AssocClass = Win32_DiskDriveToDiskPartition",
                drive["DeviceID"])).First();
    
            if (partition != null)
            {
                // associate partitions with logical disks (drive letter volumes)
                ManagementObject logical = new ManagementObjectSearcher(String.Format(
                    "associators of {{Win32_DiskPartition.DeviceID='{0}'}} " + 
                        "where AssocClass= Win32_LogicalDiskToPartition",
                    partition["DeviceID"])).First();
    
                if (logical != null)
                {
                    // finally find the logical disk entry
                    ManagementObject volume = new ManagementObjectSearcher(String.Format(
                        "select FreeSpace, Size, VolumeName from Win32_LogicalDisk " +
                         "where Name='{0}'",
                        logical["Name"])).First();
    
                    UsbDisk disk = new UsbDisk(logical["Name"].ToString());
                    disk.Model = drive["Model"].ToString();
                    disk.Volume = volume["VolumeName"].ToString();
                    disk.FreeSpace = (ulong)volume["FreeSpace"];
                    disk.Size = (ulong)volume["Size"];
    
                    disks.Add(disk);
                }
            }
        }
    
        return disks;
    }

    Intercepting Driver State Changes

    Now that we can enumerate the currently available USB disk drives, it would be nice to know when one of these goes offline or a new drive comes online. This is the purpose of the UsbManager.DriverWindow class.

    The DriverWindow class extends System.Windows.Forms.NativeWindow and is a private class encapsulated by UsbManager. The WndProc method of NativeWindow provides a convenient location to intercept and process Windows messages. The Windows message we need is WM_DEVICECHANGE and its LParam value must be DBT_DEVTYP_VOLUME. The WParam value is also important and we look for two DBT values (and an optional third).

    • DBT_DEVICEARRIVAL - broadcast when a device or piece of media has been inserted and becomes available
    • DBT_DEVICEREMOVECOMPLETE - broadcast when a device or piece of media has been physically removed
    • DBT_DEVICEQUERYREMOVE - broadcast to request permission to remove a device or piece of media; we do not process this message but it provides an opportunity to deny removal of a device

    DBT_DEVICEARRIVAL and DBT_DEVICEREMOVECOMPLETE both deliver a DEV_BROADCAST_VOLUME struct. This is actually a DEV_BROADCAST_HDR whose dbcv_devicetype is set to DBT_DEVTYP_VOLUME, so we know we can cast the packet to a DEV_BROADCAST_VOLUME.

    [StructLayout(LayoutKind.Sequential)]
    public struct DEV_BROADCAST_VOLUME
    {
        public int dbcv_size;       // size of the struct
        public int dbcv_devicetype; // DBT_DEVTYP_VOLUME
        public int dbcv_reserved;   // reserved; do not use
        public int dbcv_unitmask;   // Bit 0=A, bit 1=B, and so on (bitmask)
        public short dbcv_flags;    // DBTF_MEDIA=0x01, DBTF_NET=0x02 (bitmask)
    }

    The dbcv_unitmask field is a bitmask where each of the first 26 low-order bits correspond to a Windows drive letter. Apparently, it is possible to see a device associated with more than one drive letter but we only care about the first available for our use.

    DriverWindow fires its own StateChanged event to signal UsbManager. UsbManager then decides if it needs to retrieve information - which it does for new arrivals - and then fires its own StateChanged event to signal consumers.

    The StateChanged Event

    The demo app attached to this article shows all the power of UsbManager in just a few lines of code. It first enumerates all existing USB disk drives and displays them in a TextBox. It then wires up a handler to the UsbManager.StateChanged event. This event is defined as follows:

    public event UsbStateChangedEventHandler StateChanged

    Take a look at the StateChanged implementation and you'll notice that the add and remove statements have been extended. This allows us to instantiate a DriverWindow instance only when consumers are listening and then dispose it off when all consumers have stopped listening.

    Your handler must be declared as a UsbStateChangedEventHandler as follows:

    public delegate void UsbStateChangedEventHandler (UsbStateChangedEventArgs e);

    And the UsbStateChangedEventArgs is declared as:

    public class UsbStateChangedEventArgs : EventArgs
    {
        public UsbDisk Disk;
        public UsbStateChange State;
    }
    • The State property is an enum specifying one of Added, Removing, or Removed.
    • The Disk property is a UsbDisk instance. If State is Added, then all properties of Disk should be populated. However, if State is Removing or Removed, then only the Name property is populated since we can't detect attributes of a device that no longer exist.

    Conclusion

    If you found this article helpful and enjoy the iTuner application, please consider donating to support continual improvements of iTuner and, hopefully, more helpful articles. Thanks!

    출처 : http://www.codeproject.com/KB/cs/UsbManager.aspx

    posted by Sunny's
    2010. 8. 25. 10:47 ETC

    출처 : http://lowlevel.egloos.com/755205

    최근의 노트북과 넷북은 출시될때부터 CD-ROM이나 DVD-ROM등이 없이 나오는 경우가 많다. lowlevel도 TP-X100e 사용자이며 본인의 넷북도 ODD가 역시 없다. 그래서 이방법 저방법 알아봤다. Ultraiso를 사용할 경우 INF파일을 제대로 로드하지 못하며 잘 작동하지 않고, CD영역을 만드는 방법은 너무나 복잡하다. 그러나 WinToFlash 를 사용하면 간편하게 USB로 Windows XP를 설치할수있게 도와준다. Win to flash는 USB메모리를 bios에서 USB-HDD에 인식되게 만들어 주며 XP뿐만 아니라 2003/Vista/7/2008 까지 지원한다.

    자신있게 이야기 하지만 Windows XP/2003을 USB로 설치하는 방법중 가장 간단하고 가장 편한 방법이다. Vista와 7은 Ultraiso에서도 쉽게 바로 만들수 있을 뿐만 아니라, 자체적으로 기능이 내장되어 있다.

    이제 본격적으로 USB를 이용한 Windows XP 설치방법에 대하여 알아보자.

    아래와 같은 순서로 진행하겠다.
    1. XP를 USB로 설치할수 있게 만들어 주는 WinToFlash 다운로드
    2. XP 설치 파일을 C:\WXP 경로에 복사하기.
    3. WinToFlash 마법사를 실행하여 XP 설치가 가능한 USB 만들기
    4. 내 노트북/PC에 USB-HDD 부팅순서 설정하기.
    1. XP를 USB로 설치할수 있게 만들어 주는 WinToFlash 다운로드

    WinToFlash를 다운받으려면 아래의 URL에 접속하면 된다.
    URL : http://wintoflash.com/download/en/

    혹은 여기를 눌러 직접 다운로드 받는다. (주소가 바뀌면 다운로드가 되지 않을 것이다.)

    접속을 하게되면 가장 최신버전을 다운로드 받게 되는데 Torrent보다는 FTP로 받는것이 당장 쓰는데 훨씬 편할것이다.












    다운로드가 완료되면 원하는 위치에 압축을 풀어준다. 본인은 C:\WinToFlash에 압축을 풀었다. 본 경로는 사용자가 원하는 임의의 장소에 위치해도 상관 없다. 굳이 본 글과 똑같이 하지 않아도 된다는 것이다.














    2. XP 설치 파일을 C:\WXP 경로에 복사하기.

    이 글을 읽는 사람중 CD/DVD-ROM을 가지고 있는 사람은 내컴퓨터에서 Windows-XP 설치CD를 삽입한 미디어를 마우스 우 클릭하여 열기로 들어가 모든 파일을 C:\WXP에 복사하면 된다.

    하지만 이 글을 읽는 사람중 CD/DVD-ROM을 가지고 있지 않은 사람이 더 많을 것이며 이미지 파일로(iso 등등) 소유하고 있을 것이다. 빵집이나 알집 혹은 Ultraiso로 압축/추출이 쉽게 가능하다. 본 글에서는 Ultraiso를 이용한다.






















    해당 ISO파일을 Ultraiso를 실행하여 F4키를 누르면 ISO파일을 위와같이 내보낼수 있다. 본 글에서는 C:\WXP라는 경로에 내보내겠으나 위치는 사용자 마음대로 하면 된다. 주의할점은 내보낼 곳의 폴더는 미리 만들어 놔야 한다.

    이제 모든 준비가 끝이
    WinToFlash 마법사를 실행하여 XP 설치가 가능한 USB 만들기

    3. WinToFlash 마법사를 실행하여 XP 설치가 가능한 USB 만들기

    좀 전에 WinToFlash를 다운로드 받아 압축을 풀었던 위치로 이동한다. 본 글에서는 C:\WinToFlash에 압축을 풀었었다. 해당 경로에 이동한 후 WinToFlash.exe를 실행한다.





















    WinToFlash가 실행된 모습이다. 우리는 우선 Windows 설치 전송 마법사를 이용할 것이다. Windows 설치 전송 마법사를 클릭한다.





















    설치 전송 마법사가 실행될 것이다. 계속 진행하기 위해 다음을 클릭한다.





















    Windows 설치파일 경로에는 좀전에 Windows 설치파일을 추출시킨 C:\WXP폴더를 선택하거나 혹은 본인이 지정한 위치를 지정한다. 지정된 위치에 문제가 있을경우 다음 과정이 진행이 되지 않는다. USB 드라이브 역시 본인이 설치한 이동식 디스크 경로를 올바르게 설정하여야 한다. 모든 설정이 완료 되었다면 다음을 클릭한다.

























    해당 설치파일에서 동의 관련 파일을 로드하여 라이센스 동의를 묻는 내용이 있다. 물론 라이센스 항목에 동의하여 계속을 클릭하여 다음과정을 진행하여야 한다.















    Windows XP 설치 USB를 만들기 위해서는 USB 드라이브가 포맷된다. 위 그림은 해당 사항에 대한 경고문이며 준비가 되었다면(?) 확인을 눌러 다음과정을 진행한다.





















    파라미터를 수집하고 드라이브를 포맷하고 폴더를 복사한후 부트로더 설정후 Windows 파일을 복사하는데 이 프로그램의 유일한 단점이 속도가 느리다는 것이다. PC와 USB드라이브의 속도에 따라 차이가 있겠지만 본인의 넷북과 USB로는 20분정도가 소요 되었으며 인내심을 가지고 기다릴 필요가 있다.





















    Windows 설치파일까지 모두 복사가 완료 되면 위와 같이 나타나며 다음 버튼을 클릭한다.





















    모두 완료가 되었다는 반가운 문구가 뜰것이다. 이제는 만들어진 USB로 XP를 설치하는 일만 남았다.

    4. 내 노트북/PC에 USB-HDD 부팅순서 설정하기.

    본인의 노트북 혹은 넷북,PC가 USB-HDD부팅을 지원하는지 알아보자. 컴퓨터를 잘 모르는 초보자이면서 브랜드 PC의 사용자라면 콜센터에 물어보는것도 나쁘지는 않지만 간단한 방법이니 한번 따라해 보도록 하자. 각 제조사별로 BIOS,CMOS Setup 프로그램의 모양은 다소 차이가 있다. CMOS 설정에 진입하기 위해서는 컴퓨터의 전원이 켜지자 마자 F2 혹은 Delete키를 연타한다. 혹은 본인처럼 최초 Enter키를 누르고 F1키를 눌러야 CMOS 설정에 진입되는 뭐같은 경우도 있으니 -_-;; 본인 PC에서 CMOS 설정에 들어가는 방법을 잘 숙지하고 설정하기를 바라며, 그에 관한 문의는 받지 않는다.

    CMOS 설정에 들어갔다면 Boot Device에 관련된 설정이 있을것이다. 본인의 경우 Startup이라는 메뉴가 있었다.


















    위 처럼 USB-HDD를 첫번째 부팅장치로 두고 F10을 눌러 저장하고 부팅후 기존 Windows XP를 설치한것 처럼 계속 진행하면 된다. 또 하나 주의 할점은 파티션을 설정할때 혹시 본인이 USB의 파티션을 삭제/생성 하거나 USB에 WIndows XP를 설치하지 않나 주의있게 진행하여야 한다.

    아쉽게도 본인의 CMOS 부팅 설정에서 USB-HDD가 죽어도 안보이고 구닥다리 PC라면 여기까지 따라했던 과정이 모두 헛수고가 된다고 눈물을 흘리며 알려드린다.

    마치면서 ...

    WinToFlash의 고급작업 모드는 생략하였다. 그 이유는 귀차니즘 뿐만 아니라!! 충분히 쉽고 간편하기 때문에 혼자서 알아서 잘 할거라 믿기 때문이다. 더불어 간단한 과정을 긴글로 풀어썻는데 끝까지 읽어준 모든 분께 감사의 말씀을 전하며 이상 마치겠으며 이 글을 작성하는데 꽤 긴시간이 소모했으니 댓글 하나 받는걸로 생색을 내고 싶은 마음이다.
    posted by Sunny's
    prev 1 next