Using MFC Controls as Tk widgets

MFC topics are, of course, specific to Windows.

I wrote a C++ class that allows the use of any MFC based Windows control as a pseudo Tk widget. The class is based on a proprietary library so I cannot disclose the source code, but it was pretty straightforward, and makes only minimal use of Tk's internals.

Here's some code to get the CWnd* for a Tk widget: (Path is a char* with the widget path name, or NULL for get the application's main window):

     Tk_Window const tkmainwin = Tk_MainWindow(interp);
     if (tkmainwin==NULL)
             return NULL;

     Tk_Window const tkwin = Path==NULL
             ? tkmainwin
             : Tk_NameToWindow(interp,Path,tkmainwin);
     if (tkwin==NULL)
             return NULL;

     Window const window = Tk_WindowId(tkwin);
     if (window==NULL)
             return NULL;

     HWND const hwnd = Tk_GetHWND(window);
     if (hwnd==NULL)
             return NULL;

     CWnd *const Wnd = CWnd::FromHandle(hwnd);
     if (Wnd==NULL)
             return NULL;

     return Wnd;

Use this to find the parent window which you pass to CWnd::Create. After that, the MFC control will mostly take care of itself. In order to get geometry management right, I demand all of those MFC widgets to be the child of a standard Tk frame widget, and I use bind NameOfTheFrame <Configure> to trap moves and resizes of the frame in order to move resp. resize the MFC widget along with the frame. The MFC control isn't a real widget, e.g. it's not managed by a geometry manager (but its parent frame widget is) and it can't be removed with the destroy command (but it will be removed when its parent frame is destroyed), yet the look and feel is identical to both pure Tk and a native Windows dialog. The whole class is less than 300 lines of C++ (including comments). I successfully used it to embed a complex custom MFC widget (derived from CComboBox with a custom CEdit-derived edit control) in a Tk program.

Terminology note: control = user interface element in Windows/MFC, widget = user interface element in Tk.

Wolfram Roesler <wr at>, 12-July-2002

How does a HWND relate to a (CWnd *)? Answer: Both are handles to a window; CWnd is a C++ class which is more or less a wrapper for a HWND.