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

本文详细介绍了Windows Forms控件的消息处理流程,包括控件的构造过程、句柄创建、消息传递及处理机制等关键步骤。通过深入探讨.NET Framework中控件与原生Windows消息之间的交互方式,为读者提供了理解WinForms应用程序底层机制的重要视角。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

None.gifpublic Control()
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gifdot.gif
InBlock.gif      
this.window = new Control.ControlNativeWindow(this);
InBlock.gifdot.gif
ExpandedBlockEnd.gif}

None.gif
None.gif

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.





转载于:https://www.cnblogs.com/jeffreytan/archive/2006/08/12/475291.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值