Tricky MFC bugs

Problem connecting to ODBC data source

Problem: When calling CDaoDatabase::Open("",FALSE,FALSE,"ODBC;") an exception is raised with the error text "invalid window handle". (Also this error shows up as "OBDC -- call failed" if the exception is not caught).

Cause: The first time CDaoDatabase::Open() is called in an application appears to set the window handle for the ODBC data source selection dialog. If a window is created with a NULL parent window before the first call to the Open() function, then DAO seems to record a NULL window handle which causes the error "invalid window handle" when DAO attempts to display the Data source selection dialog.

Solution 1: Check to see if a window is being created with a NULL parent window before the first call to CDaoDatabase::Open(). If it is, pass in AfxGetMainWnd() as the parent window handle instead.

Solution 2: The following code uses undocumented functions to set the window handle used by DAO (Thanks Tero for finding this out from Microsoft and sharing the info).
COleVariant varHWND( (long)AfxGetMainWnd(), VT_I4 ); 
AfxDaoGetEngine()->SetOption( 4, varHWND );