How to cause my C++ program to wait for sensor events for ever and not terminate

僤鯓⒐⒋嵵緔 提交于 2019-12-13 02:37:28

问题


I'm trying to write a simple C++ app that registers to Windows sensor events. I followed the MSDN documentaion and managed succesfully to get notifications when sensor events occur, my problem is that my main function ends, and so does the application. How to i cuase it to wait forever for events to occur? Currently it registers and dies...

I have the following code:

My main looks like this:

int _tmain(int argc, _TCHAR* argv[])
{
   RegisterToSensorEvents();
   return 0;
}

void RegisterToSensorEvents()
{
    ISensorManager* pSensorManager = NULL;
    CoInitialize(NULL);
    HRESULT hr = ::CoCreateInstance(CLSID_SensorManager, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pSensorManager));

    // Get a collection of all sensors on the computer.
    ISensorCollection* pSensorCollection = NULL;
    hr = pSensorManager->GetSensorsByCategory(SENSOR_CATEGORY_ALL, &pSensorCollection);

    EventsManager *pEventClass = NULL;
    ISensorEvents* pMyEvents = NULL;
    pEventClass = new(std::nothrow) EventsManager();   
    hr = pEventClass->QueryInterface(IID_PPV_ARGS(&pMyEvents));

    ULONG numOfSensors;
    pSensorCollection->GetCount(&numOfSensors);
    for(int i=0; i< numOfSensors; i++)
    {
        ISensor *sensor = NULL;
        pSensorCollection->GetAt(i,&sensor);
        hr = sensor->SetEventSink(pMyEvents);
    }
}

EventsManager is a class that derives from ISensorEvents and implements its callbacks, for example:

STDMETHODIMP EventsManager::OnDataUpdated(ISensor *pSensor,ISensorDataReport *pNewData)
{
    cout  <<"got here: Data Update" << endl;
}

I tried:

 int _tmain(int argc, _TCHAR* argv[])
 {
   RegisterToSensorEvents();
   while(true){}
   return 0;
 }

but seems like this infinte loop did not leave time for the program to process the incomming events, I tried adding Sleep in the loop body, but it didn't work either.

anyone?

UPDATE:

after investigation i see that the issue is different - seems like somehow my registartion of SetEventSink gets canceled and that is why i don't get any event notification.

if i copy this line: hr = sensor->SetEventSink(pMyEvents); into my loop:

while(true)
{
   hr = sensor->SetEventSink(pMyEvents);
}

the events are fired as expected. But it sounds to me very wrong to do such a thing.

Need to understand why this is hapenning.

Can anyone help?


回答1:


Why don't you launch a new thread to do the listening, and just have the main function wait for an input?

How to simulate "Press any key to continue?"

Simple example of threading in C++

You can combine these to get your desired result.



来源:https://stackoverflow.com/questions/35693507/how-to-cause-my-c-program-to-wait-for-sensor-events-for-ever-and-not-terminate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!