Enumerating System Devices on Windows

August 11, 2006 at 5:09 PMAmer Gerzic

Occasionally an application execution depends on installed devices. For example, USB memory card might be needed for storing/reading application specific files. But how do we know that such device is inserted/installed on the system?

Below is the code that enumerates all installed devices on a windows system.

HDEVINFO hInfoList = ::SetupDiGetClassDevs(NULL, NULL, NULL,
        DIGCF_PRESENT | DIGCF_ALLCLASSES | DIGCF_PROFILE);
if(hInfoList != INVALID_HANDLE_VALUE)
{
    SP_DEVINFO_DATA spdid;
    spdid.cbSize = sizeof(SP_DEVINFO_DATA); 

    DWORD dwIndex = 0;
    while(::SetupDiEnumDeviceInfo(hInfoList, dwIndex, &spdid))
    {
        CString strEntry = _T(""); 

        TCHAR szName[4096] = {0}; 

        if(::SetupDiGetClassDescription(&spdid.ClassGuid, 
                                        szName, 
                                        4096, 
                                        NULL))
        strEntry += szName;
        strEntry += " | "; 

        if(::SetupDiGetDeviceRegistryProperty(hInfoList, &spdid, SPDRP_DEVICEDESC, 0,
            (PBYTE)szName, 4096, 0))
        {
            strEntry += szName;
        }
        
        strEntry += " | "; 

        if(::SetupDiGetDeviceRegistryProperty(hInfoList, 
                &spdid, SPDRP_FRIENDLYNAME, 0, 
                (PBYTE)szName, 4096, 0))
        {
            strEntry += szName;
        } 

        m_DevList.AddString(strEntry); 

        ++dwIndex;
    }
} 

::SetupDiDestroyDeviceInfoList(hInfoList);

Posted in: CPP | Win32 API

Tags: , , , , ,

Programmatically determine endianess of the host machine

August 4, 2006 at 5:16 PMAmer Gerzic

Couple of days ago I was asked by a fellow software developer the question regarding endianess of host machine. The question was if there is an easy way to determine if a host machine is little or big endian. At first, I was somewhat shocked that such a simple question was not already answered throughout his carrier. But then I realized that he is a VB developer (no offense intended) and that he never had to deal with questions like this. Also, I realized with growing popularity of .NET and Java, the separation between software implementation and hardware is growing exponentially. It is reality that some software developers will probably spend whole life developing successful applications without even knowing that endianess exists. Is this a good or bad thing, I leave the reader to decide.

Getting back to the question, I wrote little example that would determine if machine is little or big endian. Here is the code:

#include <iostream>
using namespace std; 

int main(int argc, char* argv[])
{
    unsigned int x = 0x00000001;
    unsigned char *p = (unsigned char*)&x;
    if(p[0]=1)
        cout << "The machine is little-endian" << endl;
    else cout << "The machine is big-endian" << endl; 

    return 0;
}

Posted in: CPP | Win32 API

Tags: