What's the difference between CreateWnd and CreateWindowHandle? - delphi

Delphi components have CreateWnd and CreateWindowHandle (and DestroyWnd and DestroyWindowHandle). They're both intended to be overridden by descendants, right? And not intended to be called except by the underlying VCL implementation?
What's the difference between them; when should either of them be overridden?

So far most of the answers here are pretty much on the mark and you would do well to heed their advice. However, there is a little more to this story. To your specific question about when you would override one or the other, I'll try and nutshell things a little bit.
CreateParams();
In general, most of the time all you really need to do is to override CreateParams(). If all you want to do is to subclass (remember Windows style "subclassing?" See Petzold's seminal work on Windows programming) an existing control class and wrap it up in a VCL control, you do this from CreateParams. You can also control what style bits are set and other various parameters. We've made the process of creating a "subclass" very easy. Just call CreateSubClass() from your CreateParams() method. See the core VCL controls for an example such as TCheckBox or TButton.
CreateWnd();
You would override this one if you need to do a little bit more with the window handle once it is created. For instance, if you have a control that is some kind of list, tree, or otherwise requires post-creation configuration, you'd do that here. Call the inherited CreateWnd, and when it returns (you know you have a valid handle if you return from CreateWnd because it will raise an exception if something went awry), just apply your extra magic. A common scenario is to take the data that is cached in an instance TStrings list and actually move it into the underlying window control. The TListBox is a classic example of this.
CreateWindowHandle();
I had to go refresh my memory on this one, but it seems this is one is rarely, if ever, overridden. In the few cases inside VCL itself, it appears that it is used to work around specific Windows version and locale oddities with some controls, such as the TEdit and TMemo. The other more clear-cut case is in TCustomForm itself. In this case it is there to support the old MDI (mutli-document interface) model. In this case MDI children cannot be created using the normal CreateWindowEx() API, you have to send a message to the MDI parent frame to actually create the handle. So the only reason to overide this method is if the actual process of creating the handle is done via a means completely different than the old tried-and-true CreateWindowEx().
I did notice that your question was merely asking about the creation process, but there are corresponding methods that are overridden in some cases for both handle destruction and the "voodoo" that sometimes surrounds handle recreation. But these are other topics that should be covered separately :-).

CreateWnd first calls CreateParams, then calls CreateWindowHandle using the created Params. Generally, you'll override CreateWnd and CreateParams rather than CreateWindowHandle.
I hope this helps!

Who does what:
CreateWnd is the general contractor that creates the fully formed window for a WinControl.
First, it has to set the required attributes for the WindowClass by calling CreateParams and making sure it is correctly registered.
Then it gets the window actually created, by calling CreateWindowHandle which returns the resulting Handle from the OS.
After that, we have a valid window able to process messages, and CreateWnd does the final grooming, adjusting different visual aspects like size, font, etc.
There is also later step done by CreateHandle, after CreateWnd is finished, to help the VCL in managing its windows (identification, parentage,...).

I'm sure that the final answer can only come from the people involved in the creation of the VCL (Allen?), but IMHO the virtual method with the least responsibility / which is lowest in the chain of calls should be overridden. That's why I have always overridden CreateParams() and CreateWindowHandle(). This looks like a good fit since they are both called by CreateWnd(), and both do only one special thing.
In the end it's probably a matter of preference.

Related

How to find out, when and why and how a component's property is changed at runtime?

I have a huge VCL Forms application in delphi and there is an option to display or hide a certain control (MyControl) on each form. Right now the traditional option is enabled, so MyControl should be hidden at runtime.
In Delphi Designer both Controls are visible. Every form is derived from a MyForm-class and in its OnCreate-Procedure the Visible-property of a MyControl (if available) is set to false (according to the traditional option enabled). This does work (as I can see with breaking points and watching expressions). For almost all forms this results in the MyControl not showing.
However for one certain form at some point the MyControl-component itself or any other part of the program sets the MyControls' visibility to true again. How do I find out where this happens?
I am using Delphi 10.1.
my approach:
I've tried to watch the visible-property through the watching-expressions-window using several breaking points. But of course the watching-expression is not available anywhere in the Code (myControl.Visible will only work if the breakingpoint is somewhere myControl is defined). I set a breaking-point anywhere I could evalute myControl.Visible but the magic seems to happen somewhere in between.
So my question: is there some kind of a global variable name, so that I can evalute and watch the visible-property wherever the debugger pauses the program?
a different approach:
I set a data- and an address-breakingpoint but they never fire. Only when I close the program they pause the program a few times.
As advised in the comments, if this is your code you can modify the property to use a Setter and then set a breakpoint on the setter. However if this is not your code and it simply exposes the variable (field) then changing the code to include a setter can be anywhere from triovial to impossible depending on what else needs to be recompiled when you make the change.
If this is your own custom component then you can redeclare an inherited property to use a setter.
If this is not your own custom component - you could make it a custom component and simply change the setter for the property.
You can set a memory breakpoint to alert you to when a memory location changes but your success with this may vary.
I encourage you to experiment with the conditions you can put on breakpoints, get the debugger to work for you.

How to change the parent class of an inherited class at runtime in Delphi?

Hi I'm developing a TControl descendant, lets name it THTMLBaseControl, at runtime that control only generates and output HTML code based on the settings of that control, so all the additional properties of the base TControl class and methods, including Windows Messaging system is really not used at runtime and causes memory overhead.
I need that control to be inherited from TControl so at design time I can use all the IDE designer stuff.
But at runtime almost all of those properties that at desingtime are needed i dont need them.
I also have all my controls inherited from that THTMLBaseControl, so creating a wrapper class per control class is not an option because it will duplicate the code a lot.
So what i need is something that at runtime, before the class is instantiated I can change the parent class so it will be instantiated based on another TControl-like class, maybe named TmyBaseControl inherited from "TComponent" as TControl Does, but that will not have all that TControl memory overhead and will only have the properties and methods needed by my THTMLBaseControl.
I really dont have a GUI at rutime is a web server that will serve only HTML, is some thing that intraweb and Raudus do, but always the issue is that all are based on TControl, so they have to be created at run time and generate a lot memory and process overhead that is not used. and maybe there could a solution so any THTMlBaseControl descendant instantiated at runtime will inherit the all properties and methods from TmyBaseControl and not from TControl.
I have seen there are ways to hack the VMT but maybe there are other solution and have not seen it. I already done changing the NewInstance, ClassParent and TnstanceSize class methods but i have to specify from which class and obviously i have to do the same steps per each inherited THTMLBaseControl class
And for the sake of all:
This is just a doubt, I need the components to be controls like TEdit, TPanel, visible and editable by the designer IDE I even could create my own TControl class but I was just thinking if I can reuse the code already existing.
Regards
You cannot change the class a run time. Once an object is instantiated, its class is fixed. You could hack the object to change its VMT pointer, making it refer to a different class, but that would still not address your main concern, which is memory usage — even if you change the VMT pointer, all the memory for the object has already been allocated; changing the VMT pointer doesn't magically make the object occupy less memory.
The first thing you could do is stop descending from TControl. As you've noted, you don't need any of the things it provides. All you want is something you can drop on a form at design time to set its properties. For that, all you need is TComponent, so make that your base class instead of TControl. Then you'll get something more like TTimer, which has no GUI. Once you've done that, you no longer need TForm, either. Instead, you can put your component on a TDataModule, which is specifically designed for managing non-visual components at design time.

Alternative to calling the Loaded method explicitly for dynamically created instances of a VCL component in Delphi 6?

I have several custom VCL components that do important tasks in their override of the TComponent Loaded() method. This creates a nuisance when creating instances dynamically since the Loaded() method is not called by the Delphi global loader during run-time, like it does for components that were placed on forms/frames at design-time. I also have to place the Loaded override in the public section of the class declaration so whatever code that creates an instance of the component can call it. Finally I have to remember to call Loaded() for dynamically created instances or subtle bugs will creep into the application, a problem that has bit me several times already.
Is there a better solution or approach to this?
If you need to call Loaded in your code you're doing it wrong. If you depend on a third party control that does, then I would fix that person's control. See below for how.
Let me make up a hypothetical example: Suppose I had 5 published properties, which once they are all loaded, can generate a complex curve or even better, generate a fractal, something that takes a long time.
At designtime I want to preview this curve, as soon as it's loaded, but I don't want the curve to be recalculated 5 times during DFM streaming, because each parameter P1 through P5 (type Double) has a SetP1 method, which invokes a protected method called Changed, and rebuilds my curve. Instead I have the SetP1 method return if csDesigning or csLoading are in the component states, and I then invoke Changed once, from Loaded. Clearly I can't rely on property setter methods alone, in all cases, to invoke all changes. So I need Loaded to tell me to do my first generation of some expensive work, that I want to be done 1 time exactly, not N times, where N is the number of DFM properties that would have been loaded that had method set procedures that invoked a method named Changed or something like that.
In your case, at runtime, you should not be relying on Loaded getting invoked at all. You should be instead, having your property set methods call Changed. If you need some way to change multiple properties at once, and then do some expensive thing only once, then implement a TMyComponent.BeginUpdate/TMyComponent.EndUpdate type of method call, and avoid extra work.
I can think of NO useful places where doing something from Loaded makes any sense, except for cases like the ones above, which should be specific to designtime and DFM based class use. I would expect a properly designed TComponent or TControl to properly initialize itself merely by being created in code, and by having its properties set.
So for my hypothetical TMyFractal component, I would do this when creating it in code without it ever having used DFM loading, or invoking Loaded:
cs := TMyFractal.Create(Self);
cs.Parent := Self; {Parent to a form}
cs.Align := alClient;
cs.BeginUpdate;
cs.P1 := 1.03; // does NOT trigger Regenerate
cs.P2 := 2.3;
cs.P3 := 2.4;
cs.P4 := 2.5;
cs.EndUpdate; // triggers expensive Regenerate method .
cs.Show;
// later someone wants to tweak only one parameter and I don't want to make them
// call regenerate:
cs.P5 := 3.0; // Each param change regenerates the whole curve when not loading or in a beginupdate block.
In my TMyFractal.Change method, I would invoke the expensive RegenerateCurve method once, each time any coefficient P1-P4 is modified at runtime, after initial setup, and once exactly when the component is streamed in from DFM, where Loaded is only used to handle the fact that I can hardly expect to do a beginupdate/endupdate in my control like I would have done in the code above.

Make sure nested child control is visible

I have a utility routine that I call when validating user input in a dialog fails. It sets focus to the offending control, beeps and displays an appropriate message to the user. This works well as long as the offending control is not hidden. Now I have to adapt this to a situation where the relevant controls are children of some kind of collapsible group boxes (possibly even nested), and I have to make sure that the "ancestor" boxes are expanded before calling SetFocus.
Now I have a few possibilities:
Build knowledge about the collapsible component into the error reporting routine. I'd like to avoid that as the routine should rather stay generic.
Pass an callback that can be called prior to (or instead of) SetFocus. This is error prone because one has to remember to pass the callback at all the relevant places.
My favourite solution would probably be an event (or overrideable method) (probably in TWinControl) that tells a container control "please make sure you and you child controls are visible" but I don't know of such a thing.
Any ideas how I can handle this situation?
Define an interface with a method called something like: EnsureVisible.
Implement it for all your components (you may need to derive your own versions of some of these components). This allows different controls to have quite different behaviour.
When a control needs to make sure it is visible it walks its parents and calls EnsureVisible if the interface is implemented.
If you don't like interfaces then do it with a custom Windows message, but you get the basic idea.
In my opinion the best solution would be a separate routine that builds knowledge about all container controls, allowing the dialog validation routine to stay generic and at the same time being focused enough to be easily tested and maintained. Something along the lines of:
procedure ForceControlVisible(C: TControl);
begin
// Recursive code
if Assigned(C.Parent) then ForceControlVisible(C.Parent);
// Code specific to each container control class
if C is TTabSheet then
begin
// Code that makes sure "C" is the active page in the PageControl
// goes here. We already know the PageControl itself is visible because
// of the recursive call.
end
else if C is TYourCollapsibleBox then
begin
// Code that handles your specific collapsible boxes goes here
end
end;
OOP-style methods that rely on virtual methods or implementing interfaces would be way more elegant, but require access to the source code of all the controls you want to use: even if you do have access to all required sources, it's preferable not to introduce any changes because it makes upgrading those controls difficult (you'd have to re-introduce your changes after getting the new files from the supplier).
Each component knows its Parent. You can walk up the list to make each parent visible.

How to explicitly release GDI handles allocated by TForm derived class owned by the Application?

A single class derived from TForm appears to hold onto GDI handles until the application is closed.
class TTestForm : public TForm {
public:
TTestForm(TComponent*);
};
std::auto_ptr<TTestForm> test(new TTestForm(NULL));
test->ShowModal();
I'm quite new to VCL, so please bear with me. This test was done with a form that contains no controls. As far as I udnerstand, all objects are owned by the Application if no owner is specified.
My application creates (and destroys) a lot of forms dynamically. 3-4 new GDI handles are allocated each time a form is displayed. Is there a way to explicitly release those GDI handles during application lifetime?
Caveat: I'm a Delphi programmer, not C++, but the VCL is basically the VCL. You can try the form's Release() method instead of free(). Or alternatively, in the OnClose event set the Action parameter passed to caFree - thats supposed to tell the VCL to free the window's resources when the form closes, rather than hiding it.
I guess another question is - do you need to keep creating/destroying the forms? Can you create them once and then reuse them?
It turns out that the leak was caused by an incorrectly set TImageList.ShareImages property.

Resources