Jeffrey&Lynny

一个温馨小家庭的.Net生活

导航

The magic of NativeWindow-- How does .Net Winform manage Win32 controls

1. Every .Net winform control inherits from System.Windows.Forms.Control class. In its constructor, you will see this key statement:

public Control()
{

      
this.window = new Control.ControlNativeWindow(this);

}



This statement will assign the control's reference to System.Windows.Forms.Control.ControlNativeWindow class.

ControlNativeWindow inherits from NativeWindow class and is designed to manage the messages of the assigned control.

2. Whenever a handle is needed for that control, Control.CreateControl method is called. And it internally will invoke its associated ControlNativeWindow.CreateHandle method with prepared CreateParams as parameter.

ControlNativeWindow.CreateHandle method first invokes System.Windows.Forms.NativeWindow.WindowClass.Create static method, which internally calls RegisterClass win32 API to register the native control class. The key point here is that the WindowClass.Callback method is stored in WNDCLASS structure as the default WndProc of registed class. Then it invokes CreateWindowEx win32 API to create the underlying win32 control.

3. When the WindowClass.Callback is called the first time, it will immediately call SetWindowLong to native DefWindowProc and then call its parent NativeWindow.AssignHandle method to start the subclass again.(NativeWindow.AssignHandle again first stores the DefWindowProc address and invokes SetWindowLong to set native control's wndproc to NativeMethods.Callback or NativeWindow.DebuggableCallback). Finally, it calls NativeMethods.Callback to handle this message.

4. NativeMethods.Callback just calls ControlNativeWindow.WndProc(override NativeWindow.WndProc) method. ControlNativeWindow.WndProc invokes ControlNativeWindow.OnMessage method, which only calls its associated Control's WndProc method. The message control is passed to Control class now!!

5. Control.WndProc acts as a .Net message filter which triggers most of the .Net control events in Winform control model. After the message processing, the message is finally passed to DefWndProc.





posted on 2006-08-12 22:36  比尔盖房  阅读(896)  评论(0编辑  收藏  举报