一个单文档程序,使用AfxEndDeferRegisterClass函数注册窗口类 wndclass 时指定的消息处理函数是:
wndcls.lpfnWndProc = DefWindowProc; 而当窗口创建的时候 CWnd::CreateEx 调用了AfxHookWindowCreate函数生成一个cbt钩子函数,此函数把窗口消息处理函数换成了afxWndProc. 为什么转了一圈换掉,而不是直接指定wndcls.lpfnWndProc = afxWndProc 呢

解决方案 »

  1.   

    First, the install-a-hook method works for window classes that are not yours or MFC's—such as the built-in classes Button, ListBox, ToolbarWindow32, and so on—as well as window classes that belong to third-party libraries. OK, so why not just call SetWindowLong to subclass the window (change the window proc) after the window is created? Because—and this is the real reason MFC must set a hook—in that case your window object would never get a chance to handle WM_CREATE and WM_NCCREATE. These messages are sent by Windows itself, from within ::CreateWindowEx when Windows is creating the window.
     Remember when I said ::CreateWindowEx is a black box to MFC? Once MFC calls CreateWindowEx, it can only wait until control returns. So in order to handle messages like WM_NCCREATE, MFC must hook up your window before it calls CreateWindowEx. But how can MFC do that when it doesn't know the HWND until CreateWindowEx returns. Catch-22. The only way out of this conundrum is to set a hook. Windows calls the CBT hook after it's created the window (so the hook function gets a valid HWND), but before it sends any messages to the window proc. Whew!
    If you're still with me, relax. The hard part is over. Earlier I said that there are two ways MFC can subclass a window. The first is when you call some Create function as described previously; the second happens when you call SubclassWindow or SubclassDlgItem. Fortunately, things are much simpler in this case because the window already exists. SubclassWindow and SubclassDlgItem subclass the window directly by calling ::SetWindowLong with GWL_WNDPROC, without using any hook subterfuge.
    There are other ways MFC can subclass a window (for example, the common dialogs require special handling), but generally they're all just variations on the set-a-hook game that I described. If you can wrap your head around that, you'll have no trouble understanding the variations. The important things to understand are why MFC needs to subclass each window with AfxWndProc in the first place (to map WM_XXX messages to your OnXXX handler functions), and how MFC uses a CBT hook to install AfxWndProc before Windows sends any messages to the window, so your app can handle messages like WM_CREATE and WM_NCCREATE. If you understand these two points well enough to explain them to your grandmother while simultaneously juggling three beanbags and a Tinky Winky doll, you're more than halfway to becoming a certified MFC guru.
      

  2.   

    i see,i see, thank you