关于SubclassWindow()和SubclassDlgItem

时间:2021-05-12 15:54:36

msdn上的解析

CWnd::SubclassWindow
BOOL SubclassWindow( HWND hWnd );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

hWnd

A handle to the window.

Remarks

Call this member function to "dynamically subclass" a window and attach it to this CWnd object. When a window is dynamically subclassed, windows messages will route through the CWnd’s message map and call message handlers in the CWnd’s class first. Messages that are passed to the base class will be passed to the default message handler in the window.

Subclass(子类化)是MFC中最常用的窗体技术之一。子类化完成两个工作:一是把窗体类对象attach到一个windows窗体实体中(即把一个窗体的hwnd赋给该类)。另外就是把该类对象的消息加入到消息路由中,使得该类可以捕获消息。

例如一个CEdit的派生类CMyEdit 只允许键入0-9, A-F, 则我们可以改写WM_CHAR消息响应函数,然后用SubclassWindow子类化到对话框的一个文本框实体上(可用GetDlgItem), 这样对话框上文本框的消息就会重定向到CMyEdit上。

SubDlgItem 与 SubclassWindow 区别不大,但前者只限定于对话框控件,后者是一切具有HWND的窗体

更详细的讨论可参见如下文章:

http://dev.csdn.net/article/16/16045.shtm