views:

330

answers:

1

This is a Windows Forms application. I have a function which captures some mouse events modally till a condition is met. For example, I would like to wait for the user to select a point in the window's client area (or optionally cancel the operation using the Escape key) before the function returns. I am using the following structure:

Application::AddMessageFilter(someFilter);
while(someFilter->HasUserSelectedAPoint_Or_HitEscapeKey()){
    Application::DoEvents();
}
Application::RemoveMessageFilter(someFilter);

This works quite nicely except for taking up nearly 100% CPU usage when control enters the while loop. I am looking for an alternative similar to what is shown below:

Application::AddMessageFilter(someFilter);
while(someFilter->HasUserSelectedAPoint_Or_HitEscapeKey()){
    // Assuming that ManagedGetMessage() below is a blocking
    // call which yields control to the OS
    if(ManagedGetMessage())
        Application::DoEvents();
}
Application::RemoveMessageFilter(someFilter);

What is the right way to use IMessageFilter and DoEvents? How do I surrender control to the OS till a message is received? Any GetMessage equivalent in the managed world?

+1  A: 

You could sleep the thread for 500ms or so between DoEvents() calls. Experiment with different values to see what feels right.

lc
+1 but I'd still love to be able to do something like GetMessage() like the good old days.
Vulcan Eager
Wow! A 10 millisecond Sleep works quite nicely. Makes sense too because evaluating the bool and calling DoEvents() on an empty event queue takes a very tiny fraction of a millisecond.
Vulcan Eager