0

In .NET windows forms application the child control object gets its native handle HWND at constructor. and before setting its parent.

while in win32 API CreateWindow function requires to create child window (WS_CHILD) to provide handle to its parent window

for example

c#
Button bt1=new Button();// the handle is create here
form1.Controls.Add(bt1); // parent is set here

c++
CreateWidnow("BUTTON","OK",WS_CHILD|WS_VISIBLE,100,100,40,20,hWndParent,1,hInstance,0);

My question is how .NET managed to create HWND for child control without specifying its parent HWND? thanks in advance

Ahmed Anter
  • 650
  • 4
  • 13
  • 1
    Look at this: `form1.Controls.Add(bt1);`, it's trivial that there is a relation between the form and the button. – Stefan Nov 09 '19 at 17:44
  • 1
    Nothing special is going on, the form is created before it child controls. So the form's Handle is always available to specify the parent. Do keep in mind that this is lazy, it doesn't happen in the constructor. The ball starts rolling when somebody sets the form's Visible property to true, typically with a Show() call. – Hans Passant Nov 09 '19 at 17:54
  • no please check Handle property immediately after constructor you will find it is set to valid handle and WS_VISIBLE is set on it already – Ahmed Anter Nov 09 '19 at 17:59
  • I don't do C++, and maybe this is a simplistic answer to your question _"without specifying its parent"_ but in `form1.Controls.Add()`, `form1` is the _parent_ that has already been instantiated (and you're `Add`ing a new control to) – EdSF Nov 09 '19 at 18:25
  • Override `OnHandleCreated` to see when that happens (the actual sequence of events). If you use a Form as a base class for another, it will be more interesting. A description [here](https://stackoverflow.com/a/55760332/7444103) – Jimi Nov 09 '19 at 18:52

0 Answers0