创建MFC控件的子类的正确方法是什么?

问题描述:

我们使用资源编辑器来布局对话框。所以说我有一个RichEditCtrl调用IDC_RICH。我想将它链接到自定义类 CMyRichEditCtrl:CRichEditCtrl 的实例,而不会失去在资源编辑器中设置属性的能力。

We layout dialogs using the resource editor. So say I have a RichEditCtrl called IDC_RICH. And I want to link it to an instance of a custom class CMyRichEditCtrl : CRichEditCtrl, without losing the ability to set properties on it in resource editor.

什么是正确的方法?你当然可以通过创建一个DDX链接的变量,改变类型为 CMyRichEditCtrl 得到一些功能。但在某些情况下,我看到人们调用代码像:

What's the right way? You can certainly get some functionality by creating a DDX-linked variable, and changing the type to CMyRichEditCtrl. But in some cases I see people calling code like:

m_Rich.SubclassDlgItem(IDC_RICH, this));

有什么区别?

EDIT:我看到的一个问题是,当我重写Create(Ex)方法,他们不会被调用。

One problem I'm seeing is that when I override Create(Ex) methods, they don't get called. It's kind of like the control is already created by the time my object gets linked to the resource identifier, pehaps?

这些窗口您使用CreateWindow(Ex)创建与资源编辑器对话框,第一个参数设置为在.rc文件中指定的类名。然后,DDX_机制将此实例化窗口与DoDataExchange()中的对话框类成员相关联。

The windows you put on a dialog with the resource editor are created using CreateWindow(Ex) with the first argument set tot he class name that is specified in the .rc file. The DDX_ mechanism then associated this instantiated window with the dialog class member in DoDataExchange().

MFC是Win32的一个层,但是MFC开发不会完全屏蔽你的Win32 。它更像是一堆类和方法,带走了MFC的一些苦涩,并提供某种形式的面向对象。 MFC对象的方法不是做真正的工作的,并且许多框架做的事情在底层,并不通知上层(即MFC对象),除非明确地挂接。 Create()是一个这样的方法,只有当你想手动创建一个控件,它不会被MFC当对象被创建时调用。 (这是一个泛化,因为有时它是,但这不在本讨论的范围之内)。

MFC is a layer over Win32 but MFC development doesn't completely shield you from Win32. It's more like a bunch of classes and methods that take away some of the drudgery of MFC and provide some form of object-orientedness. The methods of MFC object aren't the ones that are doing the real work, and much of the framework does things under the hood and doesn't notify the 'upper layer' (i.e., MFC objects) unless that is explicitly hooked up. Create() is such a method that is only there if you want to manually create a control, it's not called by MFC when the object is created. (this is a generalization because sometimes it is, but that's outside of the scope of this discussion).