获取控件实例的当前事件处理函数句柄

来源:互联网 发布:学校软件哪个好 编辑:程序博客网 时间:2024/04/29 06:10

突然想设计一个能在RunTime时,改变控件大小和位置的功能,而且要求尽量纯.NET而不用Win32的钩子。最重要的是对一般的界面设计透明,不要过多地影响普通界面设计的过程。  初步想法是,用一个类来处理一个Control,在变成设计态时,先保存现在的Mouse和Key的处理函数,并取消他们,然后用我们自己的Mouse和Key句柄替代原来的消息处理。在退出设计态时再恢复原来消息处理函数。

取消和添加消息处理有AddHandler 和 RemoveHandler ,但找了半天没有发现能获取当前控件消息函数的功能,于是Google了半天,东拼西凑了一些资料得到了下面的代码。如哪位有更好的办法,还请不吝赐教 

    Public Function GetEventSubscribers(ByVal target As ObjectByVal eventName As StringAs [Delegate]()
        
Dim WinFormsEventName As String = ("Event" & eventName)
        
Dim t As Type = target.GetType
        
Do
            
Dim fia As FieldInfo() = t.GetFields((BindingFlags.NonPublic Or (BindingFlags.Static Or BindingFlags.Instance)))
            
Dim fi As FieldInfo
            
For Each fi In fia
                
Dim d As [Delegate]
                
'Debug.WriteLine(fi.Name)
                If (fi.Name = eventName) Then
                    d 
= CType(fi.GetValue(target), [Delegate])
                    
If (Not d Is NothingThen
                        
Return d.GetInvocationList
                    
End If
                
End If
                
If (fi.Name = WinFormsEventName) Then
                    
Dim ehl As EventHandlerList = DirectCast(target.GetType.GetProperty("Events", (BindingFlags.FlattenHierarchy Or (BindingFlags.NonPublic Or BindingFlags.Instance))).GetValue(target, Nothing), EventHandlerList)
                    d 
= ehl.Item(fi.GetValue(target))
                    
If (Not d Is NothingThen
                        
Return d.GetInvocationList
                    
End If
                
End If
            
Next
            t 
= t.BaseType
        
Loop While (Not t Is Nothing)
        
Return New [Delegate](0 - 1) {}
    
End Function
原创粉丝点击