Método IPortableDevice::Open (portabledeviceapi.h)

El método Open abre una conexión entre la aplicación y el dispositivo.

Sintaxis

HRESULT Open(
  [in] LPCWSTR               pszPnPDeviceID,
  [in] IPortableDeviceValues *pClientInfo
);

Parámetros

[in] pszPnPDeviceID

Puntero a una cadena terminada en null que contiene la cadena de identificador de Plug and Play para el dispositivo. Puede obtener esta cadena llamando a IPortableDeviceManager::GetDevices.

[in] pClientInfo

Puntero a una interfaz IPortableDeviceValues que contiene información que identifica la aplicación al dispositivo. Esta interfaz contiene pares PROPERTYKEY/value que intentan identificar una aplicación de forma única. Aunque se requiere la presencia de una interfaz CoCreated, la aplicación no es necesaria para enviar ningún par clave-valor. Sin embargo, el envío de datos podría mejorar el rendimiento. Los pares clave-valor típicos incluyen el nombre de la aplicación, la versión principal y secundaria, y el número de compilación.

Vea las propiedades que comienzan por "WPD_CLIENT_" en la sección Propiedades .

Valor devuelto

El método devuelve un valor HRESULT. Entre los valores posibles se incluyen los que se indican en la tabla siguiente, entre otros.

Código devuelto Descripción
S_OK
El método se ha llevado a cabo de forma correcta.
E_WPD_DEVICE_ALREADY_OPENED
La conexión del dispositivo ya se ha abierto.
E_POINTER
Al menos uno de los argumentos era un puntero NULL.

Comentarios

Se debe abrir un dispositivo para poder llamar a cualquier método en él. (Tenga en cuenta que los métodos IPortableDeviceManager no requieren que abra un dispositivo antes de llamar a cualquier método). Sin embargo, normalmente no es necesario llamar a Close.

Los administradores pueden restringir el acceso de dispositivos portátiles a equipos que se ejecutan en una red. Por ejemplo, un administrador puede restringir a todos los usuarios invitados el acceso de solo lectura, mientras que a los usuarios autenticados se les concede acceso de lectura y escritura.

Debido a estos problemas de seguridad, si la aplicación no realizará operaciones de escritura, debe llamar al método Open y solicitar acceso de solo lectura especificando GENERIC_READ para la propiedad WPD_CLIENT_DESIRED_ACCESS que proporciona en el parámetro pClientInfo .

Si la aplicación requiere operaciones de escritura, debe llamar al método Open como se muestra en el código de ejemplo siguiente. La primera vez, debe solicitar acceso de lectura y escritura pasando la propiedad WPD_CLIENT_DESIRED_ACCESS predeterminada en el parámetro pClientInfo . Si se produce un error en esta primera llamada y devuelve E_ACCESSDENIED, la aplicación debe llamar al método Open una segunda vez y solicitar acceso de solo lectura especificando GENERIC_READ para la propiedad WPD_CLIENT_DESIRED_ACCESS que proporciona en el parámetro pClientInfo .

Las aplicaciones que residen en apartamentos de un solo subproceso deben usar CLSID_PortableDeviceFTM, ya que esto elimina la sobrecarga de serialización de punteros de interfaz. CLSID_PortableDevice sigue siendo compatible con las aplicaciones heredadas.

Ejemplos


#define CLIENT_NAME         L"My WPD Application"
#define CLIENT_MAJOR_VER    1
#define CLIENT_MINOR_VER    0
#define CLIENT_REVISION     0

HRESULT OpenDevice(LPCWSTR wszPnPDeviceID, IPortableDevice** ppDevice)
{
    HRESULT                hr                 = S_OK;
    IPortableDeviceValues* pClientInformation = NULL;
    IPortableDevice*       pDevice            = NULL;

    if ((wszPnPDeviceID == NULL) || (ppDevice == NULL))
    {
        hr = E_INVALIDARG;
        return hr;
    }

    // CoCreate an IPortableDeviceValues interface to hold the client information.
    hr = CoCreateInstance(CLSID_PortableDeviceValues,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_IPortableDeviceValues,
                          (VOID**) &pClientInformation);
    if (SUCCEEDED(hr))
    {
        HRESULT ClientInfoHR = S_OK;

        // Attempt to set all properties for client information. If we fail to set
        // any of the properties below it is OK. Failing to set a property in the
        // client information isn't a fatal error.
        ClientInfoHR = pClientInformation->SetStringValue(WPD_CLIENT_NAME, CLIENT_NAME);
        if (FAILED(ClientInfoHR))
        {
           // Failed to set WPD_CLIENT_NAME
        }

        ClientInfoHR = pClientInformation->SetUnsignedIntegerValue(WPD_CLIENT_MAJOR_VERSION, CLIENT_MAJOR_VER);
        if (FAILED(ClientInfoHR))
        {
            // Failed to set WPD_CLIENT_MAJOR_VERSION
        }

        ClientInfoHR = pClientInformation->SetUnsignedIntegerValue(WPD_CLIENT_MINOR_VERSION, CLIENT_MINOR_VER);
        if (FAILED(ClientInfoHR))
        {
            // Failed to set WPD_CLIENT_MINOR_VERSION
        }

        ClientInfoHR = pClientInformation->SetUnsignedIntegerValue(WPD_CLIENT_REVISION, CLIENT_REVISION);
        if (FAILED(ClientInfoHR))
        {
            // Failed to set WPD_CLIENT_REVISION
        }
    }
    else
    {
        // Failed to CoCreateInstance CLSID_PortableDeviceValues for client information
    }

        ClientInfoHR = pClientInformation->SetUnsignedIntegerValue(WPD_CLIENT_SECURITY_QUALITY_OF_SERVICE, SECURITY_IMPERSONATION);
        if (FAILED(ClientInfoHR))
        {
            // Failed to set WPD_CLIENT_SECURITY_QUALITY_OF_SERVICE
        }

    if (SUCCEEDED(hr))
    {
        // CoCreate an IPortableDevice interface
        hr = CoCreateInstance(CLSID_PortableDeviceFTM,
                              NULL,
                              CLSCTX_INPROC_SERVER,
                              IID_IPortableDevice,
                              (VOID**) &pDevice);

        if (SUCCEEDED(hr))
        {
            // Attempt to open the device using the PnPDeviceID string given
            // to this function and the newly created client information.
            // Note that we're attempting to open the device the first 
            // time using the default (read/write) access. If this fails
            // with E_ACCESSDENIED, we'll attempt to open a second time
            // with read-only access.
            hr = pDevice->Open(wszPnPDeviceID, pClientInformation);
            if (hr == E_ACCESSDENIED)
            {
                 // Attempt to open for read-only access
                 pClientInformation->SetUnsignedIntegerValue(
                       WPD_CLIENT_DESIRED_ACCESS,
                       GENERIC_READ);
                 hr = pDevice->Open(wszPnPDeviceID, pClientInformation);
            }
            if (SUCCEEDED(hr))
            {
                // The device successfully opened, obtain an instance of the Device into
                // ppDevice so the caller can be returned an opened IPortableDevice.
                hr = pDevice->QueryInterface(IID_IPortableDevice, (VOID**)ppDevice);
                if (FAILED(hr))
                {
                    // Failed to QueryInterface the opened IPortableDevice
                }
            }
        }
        else
        {
            // Failed to CoCreateInstance CLSID_PortableDevice
        }
    }

    // Release the IPortableDevice when finished
    if (pDevice != NULL)
    {
        pDevice->Release();
        pDevice = NULL;
    }

    // Release the IPortableDeviceValues that contains the client information when finished
    if (pClientInformation != NULL)
    {
        pClientInformation->Release();
        pClientInformation = NULL;
    }

    return hr;
}

Requisitos

Requisito Value
Plataforma de destino Windows
Encabezado portabledeviceapi.h
Library PortableDeviceGUIDs.lib

Consulte también

Establecimiento de una conexión

IPortableDevice (interfaz)

IPortableDevice::Close