调用服务方法

WpdServicesApiSample 应用程序包含的代码演示了应用程序如何以同步方式调用给定联系人服务支持的方法。 此示例使用以下接口

接口 说明
IPortableDeviceService 用于检索 IPortableDeviceServiceMethods 接口,以调用给定服务上的方法。
IPortableDeviceServiceMethods 用于调用服务方法。
IPortableDeviceValues 用于保存传出方法参数和传入方法结果。 如果方法不需要任何参数或返回任何结果,则可以为 NULL 。

 

当用户在命令行中选择选项“9”时,应用程序将调用在 ServiceMethods.cpp 模块中找到的 InvokeMethods 方法。 请注意,在调用方法之前,示例应用程序会在连接的设备上打开联系人服务。

服务方法封装每个服务定义和实现的功能。 它们对每种类型的服务都是唯一的,由 GUID 表示。 例如,Contacts 服务定义应用程序调用的 BeginSync 方法以准备设备以同步 Contact 对象,并定义 EndSync 方法以通知设备同步已完成。 应用程序通过调用 IPortableDeviceServiceMethods::Invoke 来执行方法。

不应将服务方法与 WPD 命令混淆。 WPD 命令是标准 WPD 设备驱动程序接口 (DDI) 的一部分,是 WPD 应用程序和驱动程序之间通信的机制。 命令是预定义的,按类别分组(例如 ,WPD_CATEGORY_COMMON),由 PROPERTYKEY 结构表示。 应用程序通过调用 IPortableDeviceService::SendCommand 将命令发送到设备驱动程序。 有关详细信息,请参阅命令主题。

InvokeMethods 方法调用 IPortableDeviceService::Methods 方法以检索 IPortableDeviceServiceMethods 接口。 使用此接口,它通过调用 IPortableDeviceServiceMethods::Invoke 方法调用 BeginSync 和 EndSync 方法。 每次调用 Invoke 时,应用程序都会为调用的方法提供 REFGUID。

以下代码使用 InvokeMethods 方法。

// Invoke methods on the Contacts Service.
// BeginSync and EndSync are methods defined by the FullEnumerationSync Device Service.
void InvokeMethods(IPortableDeviceService* pService)
{
    HRESULT hr = S_OK;
    CComPtr<IPortableDeviceServiceMethods> pMethods;

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

    // Get an IPortableDeviceServiceMethods interface from the IPortableDeviceService interface to
    // invoke methods.
    hr = pService->Methods(&pMethods);
    if (FAILED(hr))
    {
        printf("! Failed to get IPortableDeviceServiceMethods from IPortableDeviceService, hr = 0x%lx\n",hr);
    }

    // Invoke() the BeginSync method
    if (SUCCEEDED(hr))
    {
        // This method does not take any parameters or results, so we pass in NULL
        hr = pMethods->Invoke(METHOD_FullEnumSyncSvc_BeginSync, NULL, NULL);
        if (SUCCEEDED(hr))
        {
            printf("%ws called, hr = 0x%lx\n",NAME_FullEnumSyncSvc_BeginSync, hr);
        }
        else
        {
            printf("! Failed to invoke %ws, hr = 0x%lx\n",NAME_FullEnumSyncSvc_BeginSync, hr);
        }
    }

    // Invoke the EndSync method asynchronously
    if (SUCCEEDED(hr))
    {
        // This method does not take any parameters or results, so we pass in NULL
        hr = pMethods->Invoke(METHOD_FullEnumSyncSvc_EndSync, NULL, NULL);
        if (SUCCEEDED(hr))
        {
            printf("%ws called, hr = 0x%lx\n",NAME_FullEnumSyncSvc_EndSync, hr);
        }
        else
        {
            printf("! Failed to invoke %ws, hr = 0x%lx\n",NAME_FullEnumSyncSvc_EndSync, hr);
        } 
    }
}

IPortableDeviceService

IPortableDeviceServiceMethods

WpdServicesApiSample