Why TForm.Handle is a getter instead of a field?

六月ゝ 毕业季﹏ 提交于 2019-12-02 10:00:39

问题


I was debugging a complicated bug recently. It was caused by accessing a non-existing Form.Handle (garbaged pointer). The bug revealed itself in rather unexpected way for me - accessing Forms Handle caused resizes and repaints.

I would expect accessing Form.Handle by a garbage pointer would just return some garbage THandle. Expecting that the Handle is created once on form creation and stays the same till the Form is destroyed.

The question

Why is it so, that TForm.Handle is not a field that gets initialized on form creation and is accessed via

property Handle: Integer read FHandle;

, but is a getter

property Handle: Integer read GetHandle;

that creates the Handle and even the Window (CreateWnd) on first access?


回答1:


The form object can exist even when the underlying OS window doesn't. During those times, the Handle field would be 0, which isn't helpful to code that needs a valid window handle. To ensure you get a valid handle each time you need one, you'd need to call HandleNeeded prior to referring to the Handle field. As a property with a getter, the property can call HandleNeeded for you automatically, making it easier to use the Handle property.



来源:https://stackoverflow.com/questions/37614161/why-tform-handle-is-a-getter-instead-of-a-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!