Get Component's Parent Form

后端 未结 10 1017
再見小時候
再見小時候 2020-12-03 01:40

I have a non-visual component which manages other visual controls.

I need to have a reference to the form that the component is operating on, but i don\'t know how

10条回答
  •  萌比男神i
    2020-12-03 01:54

    Thanks Rob, I used your solution in a VB.Net program, looks like this:

    ''' 
    ''' Returns the parent System.Windows.form of the control
    ''' 
    ''' 
    ''' First parent form or null if no parent found
    ''' 
    Public Shared Function GetParentForm(ByVal parent As Control) As Form
        Dim form As Form = TryCast(parent, Form)
        If form IsNot Nothing Then
            Return form
        End If
    
        If parent IsNot Nothing Then
            ' Walk up the control hierarchy
            Return GetParentForm(parent.Parent)
        End If
    
        ' Control is not on a Form
        Return Nothing
    End Function
    

    Referenced it on my blog: http://www.dailycode.info/Blog/post/2012/07/03/How-to-get-a-user-controls-parent-form-(Windows-forms).aspx

提交回复
热议问题