Vb.net 防止开发人员在设计时多次放置UserControl

Vb.net 防止开发人员在设计时多次放置UserControl,vb.net,winforms,user-controls,visual-studio-2017,Vb.net,Winforms,User Controls,Visual Studio 2017,我正在研究一个UserControl,我正在寻找一种方法来防止开发人员将这个UserControl多次放入表单中。所有这些都是在设计阶段完成的。换句话说,在设计时,我如何检测我的UserControl是否已放入ParentForm!!!,如果已经有第二个位置,是否阻止第二个位置 我试过下面这个例子。。。首先我不确定这是否是正确的方法,其次我找不到如何删除或停止UserControl的放置,以防已经有了UserControl 再一次,所有这些,在设计阶段 由于这种形式易于使用和处理,因此在beat

我正在研究一个UserControl,我正在寻找一种方法来防止开发人员将这个UserControl多次放入表单中。所有这些都是在设计阶段完成的。换句话说,在设计时,我如何检测我的UserControl是否已放入ParentForm!!!,如果已经有第二个位置,是否阻止第二个位置

我试过下面这个例子。。。首先我不确定这是否是正确的方法,其次我找不到如何删除或停止UserControl的放置,以防已经有了UserControl

再一次,所有这些,在设计阶段


由于这种形式易于使用和处理,因此在beat-weans形式中不起作用。只有在这个相同的地方。您可以使用互斥体或此模块属性的某个单例瞬间,或其他通知方法,告知此模块已创建以及何时被释放

    Sub New()
    '  This call is required by the designer.
    InitializeComponent()

    If Not co Is Nothing Then Throw New Exception
    co = Me ' assign public propert in  module or singleton

    ' Add any initialization after the InitializeComponent() call.

End Sub

结束模块最后我结束了这个

Private Sub Me_ParentChanged(sender As Object, e As EventArgs) Handles Me.ParentChanged

    Dim _ParentForm = DirectCast(Me.FindForm, Control)
    Dim _ControlName As String

    If _ParentForm IsNot Nothing Then
        For Each _Control As Control In _ParentForm.Controls
            If TypeOf _Control Is MyUserControl AndAlso _Control IsNot Me Then
                Throw New ArgumentOutOfRangeException("", "You can place only one " & _ControlName & " control per form.")
            End If
            _Control = _ParentForm.GetNextControl(_Control, True)
        Next
    End If

End Sub

使用winforms添加标记?Q&D方法是在加载事件处理程序中引发异常。消息框不会赢得任何奖品,但您肯定会阻止添加第二个控件。非Q方式是创建自己的设计器。@IvanH:是的,winforms!嗯,这是我不想回答的问题,您想从中派生的设计器类是内部的。使用一个好的反编译器,查看System.Design.dll中的UserControlDocumentDesigner类。复制/粘贴其代码。它已经接近你想要的了,它的CanDropComponents方法现在可以防止主菜单被删除。当设置站点属性时,你可以访问你需要的所有内容。我已经向你展示了这个技巧。您可以迭代host.Container.Components集合以确定是否存在以前的实例。如果存在以前的实例,请使用“host.DestroyComponentMe”删除新实例。
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
    Try
        If disposing AndAlso components IsNot Nothing Then
            components.Dispose()
        End If
    Finally
        co = Nothing
        MyBase.Dispose(disposing)
    End Try
End Sub
Module common
Property co As UserControl1
Private Sub Me_ParentChanged(sender As Object, e As EventArgs) Handles Me.ParentChanged

    Dim _ParentForm = DirectCast(Me.FindForm, Control)
    Dim _ControlName As String

    If _ParentForm IsNot Nothing Then
        For Each _Control As Control In _ParentForm.Controls
            If TypeOf _Control Is MyUserControl AndAlso _Control IsNot Me Then
                Throw New ArgumentOutOfRangeException("", "You can place only one " & _ControlName & " control per form.")
            End If
            _Control = _ParentForm.GetNextControl(_Control, True)
        Next
    End If

End Sub