I have a function in my app which has to wait for a mouse click or an escape keypress before it returns. The app has to 'stay alive' until I get a result, ie the ribbon controls need to be able to update, and I need to do some of my own GDI drawing with each mouse movement etc.
I have achieved this by using a message loop. Simplified code:
bool cancel = false;
bool clicked = false;
BOOL waitForClick (CPoint &clickedPosition)
{
while (theApp.PumpMessage())
{
theApp.OnIdle(0);
if (bCancelled)
{
cancel = true;
break;
}
if (bClicked)
{
clicked = true;
break;
}
}
if (cancel)
{
return FALSE;
}
if (clicked)
{
clickedPosition = gPosition;
return TRUE;
}
return FALSE;
}
This seems to work OK but having researched this I have read a lot about how I should be using threads instead of message loops.
However, even if I spawn a thread to wait for a click, I still have to wait for that thread to finish and tell my function that it can return, right?
I also found that I can't stop this loop from elsewhere in my code. For example, suppose the user decides to run a different command, by hitting another ribbon button. I need to cancel the command currently running (which is the loop above). I tried making the loop check a global bool is true every time through the loop, and set that bool to false if the other command starts, but of course the loop isn't passed through until the code for that other command has finished.
Another problem is that in an MDI environment, if I start the command, switch documents, start the command in that document, and then switch back to the first document, I now have the loop running in the second document, hogging all the messages.
So in summary, I don't think a message loop is the right answer. But I don't get how threading could do it either, in this case, mainly because
the function can not return until it has a click or an escape.
I would guess that there is an elegant solution to this, probably using threading, which so far has escaped me (no pun intended). Is anyone able to give me a nudge in the right direction please?