检索传感器对象

若要检索传感器对象,请使用 ISensorManager 接口。 可以将此接口视为传感器 API 的根接口。 若要使用 ISensorManager,必须先调用 COM CoCreateInstance 方法。

以下示例代码创建传感器管理器的实例。

// Create the sensor manager.
hr = CoCreateInstance(CLSID_SensorManager, 
                        NULL, CLSCTX_INPROC_SERVER,
                        IID_PPV_ARGS(&pSensorManager));

if(hr == HRESULT_FROM_WIN32(ERROR_ACCESS_DISABLED_BY_POLICY))
{
    // Unable to retrieve sensor manager due to 
    // group policy settings. Alert the user.
}

成功检索指向 ISensorManager 的指针后,可以按类别、类型或 ID 检索传感器。 如果按类型或类别检索传感器,则会收到一个指向 ISensorCollection 接口的指针,该接口包含属于所请求类别或类型的所有可用传感器。 如果按传感器 ID 检索传感器,则会收到一个指向 ISensor 接口的指针,该接口表示所请求的唯一传感器。

以下示例代码检索属于名为 SAMPLE_SENSOR_CATEGORY_DATE_TIME 类别的传感器集合。 然后,代码按索引检索集合中的第一个传感器。

// Get the sensor collection.
hr = pSensorManager->GetSensorsByCategory(SAMPLE_SENSOR_CATEGORY_DATE_TIME, &pSensorColl);
  
if(SUCCEEDED(hr))
{
    ULONG ulCount = 0;

    // Verify that the collection contains
    // at least one sensor.
    hr = pSensorColl->GetCount(&ulCount);

    if(SUCCEEDED(hr))
    {
        if(ulCount < 1)
        {
            wprintf_s(L"\nNo sensors of the requested category.\n");
            hr = E_UNEXPECTED;
        }
    }
}

if(SUCCEEDED(hr))
{
    // Get the first available sensor.
    hr = pSensorColl->GetAt(0, &pSensor);
}

请注意,可以使用 SENSOR_CATEGORY_ALL 检索所有可用的传感器。

同样,可以检索特定类型的传感器。

以下示例代码检索名为 SAMPLE_SENSOR_TYPE_TIME 类型的传感器集合。 然后,代码按索引检索集合中的第一个传感器。

// Get the sensor collection.
hr = pSensorManager->GetSensorsByType(SAMPLE_SENSOR_TYPE_TIME, &pSensorColl);
  
if(SUCCEEDED(hr))
{
    ULONG ulCount = 0;

    // Verify that the collection contains
    // at least one sensor.
    hr = pSensorColl->GetCount(&ulCount);

    if(SUCCEEDED(hr))
    {
        if(ulCount < 1)
        {
            wprintf_s(L"\nNo sensors of the requested type.\n");
            hr = E_UNEXPECTED;
        }
    }
}

if(SUCCEEDED(hr))
{
    // Get the first available sensor.
    hr = pSensorColl->GetAt(0, &pSensor);
}

若要按传感器 ID 检索传感器,必须知道传感器的唯一 ID。 传感器通常在首次连接时生成此 ID,以便识别同一个型号和型号的多个传感器。 这意味着你可能无法提前知道传感器 ID。 但是,如果存储了之前检索到的特定传感器 ID 的副本(例如通过调用 ISensor::GetID),则可能需要再次检索同一传感器。

以下示例代码演示如何使用传感器 ID 检索传感器。

ISensor* pSensor = NULL;

// Get the sensor collection.
hr = pSensorManager->GetSensorByID(SAMPLE_SENSOR_TIME_ID, &pSensor);

还可以通过从传感器管理器接收事件,在传感器变为可用时检索传感器。 有关详细信息,请参阅 ISensorManager::SetEventSink

ISensorManagerEvents::OnSensorEnter