Partilhar via


Enumerando conteúdo

O conteúdo em um dispositivo (seja uma pasta, um catálogo telefônico, um vídeo ou uma imagem estática) é chamado de objeto na API WPD. Esses objetos são referenciados por identificadores de objeto e descritos por propriedades. Você pode enumerar os objetos em um dispositivo chamando métodos no de interface IPortableDevice , o interface IPortableDeviceContente o interface IEnumPortableDeviceObjectIDs.

O aplicativo de exemplo demonstra a enumeração de conteúdo na função EnumerateAllContent que é encontrada no módulo ContentEnumeration.cpp. Essa função, por sua vez, chama uma função RecursiveEnumerate que percorre a hierarquia de objetos encontrados no dispositivo selecionado e retorna um identificador de objeto para cada objeto.

Como observado, a função RecursiveEnumerate recupera um identificador de objeto para cada objeto encontrado no dispositivo. O identificador de objeto é um valor de cadeia de caracteres. Depois que seu aplicativo recupera esse identificador, ele pode obter mais informações descritivas do objeto (como o nome do objeto, o identificador do pai do objeto e assim por diante). Essas informações descritivas são chamadas de propriedades do objeto (ou metadados). Seu aplicativo pode recuperar essas propriedades chamando membros do interface IPortableDeviceProperties.

A função EnumerateAllContent começa recuperando um ponteiro para um interface IPortableDeviceContent. Ele recupera esse ponteiro chamando o método IPortableDevice::Content.

void EnumerateAllContent(
    IPortableDevice* pDevice)
{
    HRESULT                         hr = S_OK;
    CComPtr<IPortableDeviceContent> pContent;

    if (pDevice == NULL)
    {
        printf("! A NULL IPortableDevice interface pointer was received\n");
        return;
    }

    // Get an IPortableDeviceContent interface from the IPortableDevice interface to
    // access the content-specific methods.
    hr = pDevice->Content(&pContent);
    if (FAILED(hr))
    {
        printf("! Failed to get IPortableDeviceContent from IPortableDevice, hr = 0x%lx\n",hr);
    }

    // Enumerate content starting from the "DEVICE" object.
    if (SUCCEEDED(hr))
    {
        printf("\n");
        RecursiveEnumerate(WPD_DEVICE_OBJECT_ID, pContent);
    }
}

Depois de recuperar o ponteiro para a interface IPortableDeviceContent, a função EnumerateAllContent chama a função RecursiveEnumerate, que percorre a hierarquia de objetos encontrados no dispositivo determinado e retorna um identificador de objeto para cada um.

A função RecursiveEnumerate começa recuperando um ponteiro para um interface IEnumPortableDeviceObjectIDs. Essa interface expõe os métodos que um aplicativo usa para navegar na lista de objetos encontrados em um determinado dispositivo.

Neste exemplo, a função RecursiveEnumerate chama o método IEnumPortableDeviceObjectIDs::Next para percorrer a lista de objetos.

Cada chamada para o método IEnumPortableDeviceObjects::Next solicita um lote de 10 identificadores. (Esse valor é especificado pela constante NUM_OBJECTS_TO_REQUEST fornecida como o primeiro argumento.)

#define NUM_OBJECTS_TO_REQUEST  10

// Recursively called function which enumerates using the specified
// object identifier as the parent.
void RecursiveEnumerate(
    PCWSTR                  pszObjectID,
    IPortableDeviceContent* pContent)
{
    CComPtr<IEnumPortableDeviceObjectIDs> pEnumObjectIDs;

    // Print the object identifier being used as the parent during enumeration.
    printf("%ws\n",pszObjectID);

    // Get an IEnumPortableDeviceObjectIDs interface by calling EnumObjects with the
    // specified parent object identifier.
    HRESULT hr = pContent->EnumObjects(0,               // Flags are unused
                                       pszObjectID,     // Starting from the passed in object
                                       NULL,            // Filter is unused
                                       &pEnumObjectIDs);
    if (FAILED(hr))
    {
        printf("! Failed to get IEnumPortableDeviceObjectIDs from IPortableDeviceContent, hr = 0x%lx\n",hr);
    }

    // Loop calling Next() while S_OK is being returned.
    while(hr == S_OK)
    {
        DWORD  cFetched = 0;
        PWSTR  szObjectIDArray[NUM_OBJECTS_TO_REQUEST] = {0};
        hr = pEnumObjectIDs->Next(NUM_OBJECTS_TO_REQUEST,   // Number of objects to request on each NEXT call
                                  szObjectIDArray,          // Array of PWSTR array which will be populated on each NEXT call
                                  &cFetched);               // Number of objects written to the PWSTR array
        if (SUCCEEDED(hr))
        {
            // Traverse the results of the Next() operation and recursively enumerate
            // Remember to free all returned object identifiers using CoTaskMemFree()
            for (DWORD dwIndex = 0; dwIndex < cFetched; dwIndex++)
            {
                RecursiveEnumerate(szObjectIDArray[dwIndex],pContent);

                // Free allocated PWSTRs after the recursive enumeration call has completed.
                CoTaskMemFree(szObjectIDArray[dwIndex]);
                szObjectIDArray[dwIndex] = NULL;
            }
        }
    }
}

Interface IEnumPortableDeviceObjectIDs

IPortableDevice Interface

Interface IPortableDeviceContent

Interface IPortableDeviceProperties

Guia de Programação