zig
zig

Reputation: 4624

Accessing TWinControl.Handle on TForm.Create

I have this code:

procedure TForm1.FormCreate(Sender: TObject);
begin
  DoSomethingWithCombobox(ComboBox1.Handle);
end;

Q: Is it guaranteed that the ComboBox1.Handle is always created on TForm.FormCreate (Form1 is the parent of ComboBox1)? Maybe on OnFormShow? from my tests, it seems that the Handle is always available at that point.

I know that ComboBox1.Handle will call HandleNeeded at this point. but can I assume that Handle will always be available at this point?

I also know that the TWincontrol can safely access it's own handle on CreateWnd. My question is specific to a scenario where I cannot control CreateWnd of the child control and only have access to the parent events/messages.

Hope my question is clear.

Upvotes: 1

Views: 310

Answers (1)

Rob Kennedy
Rob Kennedy

Reputation: 163357

If your tests show that it's OK to access the control's handle there, then it should be OK. You're the application developer, so if you later change anything to break that assumption, you'll also have the power to fix it.

Accessing a control's Handle property will either yield a valid window handle or throw an exception. You won't get a null handle. The exception would typically come when the control's parent window is unable to exist.

The handle you get at that point isn't guaranteed to be the last handle the control will ever have, because controls' underlying windows may be recreated, but since you're the application developer (as opposed to a component-library developer), you have reasonable control over how often windows will be recreated after the form has finished being created. This is because you're handling the OnCreate event. Had you been overriding the Loaded method, for example, there's be less confidence that all window-creation activity had finished.

Upvotes: 2

Related Questions