Compartilhar via


Instantiating the WPD Automation Factory Interface

WPD Automation can be instantiated from C++/COM by CoCreating IPortableDeviceDispatchFactory and calling IPortableDeviceDispatchFactory::GetDeviceDispatch, supplying a Device Plug and Play (PnP) identifier. The DevicePnPId is a string that represents a WPD device, and is returned by the IPortableDeviceManager::GetDevices method in the WPD C++/COM API.

The following example shows how to instantiate and return a WPD Automation Device object. The code can be wrapped in an IDispatch method for an ActiveX object that is accessible from JScript.

IFACEMETHODIMP CMyDeviceFactory::GetFirstDeviceObject(IDispatch** ppDeviceObject)
{
    ComPtr<IPortableDeviceManager> spDeviceManager;

    HRESULT hr = CoCreateInstance(CLSID_PortableDeviceManager, 
NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&amp;spDeviceManager));

    if (SUCCEEDED(hr))
    {
        // For simplicity, the following code sample retrieves the first 
        // device, if available.

        LPWSTR pszDevicePnPID = NULL;
        DWORD cDevices = 1;
        hr = spDeviceManager->GetDevices(pszDevicePnPID, &amp;cDevices);

        if (SUCCEEDED(hr) &amp;&amp; cDevices > 0)
        {
            CComPtr<IPortableDeviceDispatchFactory> spDeviceDispatchFactory;
            hr = CoCreateInstance(CLSID_PortableDeviceDispatchFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&amp;spDeviceDispatchFactory));

            if (SUCCEEDED(hr))
            {
                hr = spDeviceDispatchFactory->GetDeviceDispatch(pszDevicePnPID, ppDeviceObject);
            }
        }

        CoTaskMemFree(pszDevicePnPID);
    }

    return hr;
}

The following example shows how to instantiate a Device object from JScript by calling CMyDeviceFactory through IDispatch.

var deviceFactory = new ActiveXObject("MyControl.MyDeviceFactory");

// Get the first device object from the device factory
var deviceObject = deviceFactory.GetFirstDeviceObject();

About the Device Object

Best Practices for Writing WPD Automation Scripts

IPortableDeviceDispatchFactory Interface

Using WPD Automation

Windows Portable Devices Programming Reference