Archive for June, 2012

You’re not gonna catch this…

Thursday, June 14th, 2012

You're not gonna catch this... (LIttle League baseball, May 2009 - 03 by Ed Yourdon; CC BY-SA 2.0)

C++ exceptions can be surprising. This works easily:

catch(…) //Catch all

But if you replace “throw(1);” with “throw;”, it suddenly doesn’t work anymore. Code compiles, exception is thrown, but it’s not caught. The program is terminated

MFC: Redirecting OnMouseWheel messages to the window under cursor

Wednesday, June 6th, 2012

By default MFC applies the MouseWheel message to the window that has the focus. Even though most users expect it to apply to the window under the cursor. (And even Microsoft’s style guide recommends that.)

To fix this, override the program’s PreTranslateMessage ¬†function and add this:

 if (pMsg->message==WM_MOUSEWHEEL)
    CPoint point;
    GetCursorPos (&point);

    HWND hWnd = ::WindowFromPoint (point);

    if (hWnd && pMsg->hwnd!=hWnd)
       ::PostMessage(hWnd, pMsg->message, pMsg->wParam, pMsg->lParam);

Please note that you have to add this  before calling the default implementation of PreTranslateMessage.

Turning off floating point exceptions against crashes

Friday, June 1st, 2012

It sounds quite mad, but either of these lines can crash a program: (C++, Visual Studio 2005)

long x = long(my_float_var);
float f = exp(my_float_var);

If the number is too large/small, the program is terminated. (No, try/catch doesn’t help.) And to make it even stranger, this happens only on some computers. And of course it happened on the customer’s computer and not on mine…

To fix this, it helps to turn off the floating point exceptions:

Of course the problem of the large number still exists, but now the program at least continues to run, and I have a chance to handle it.