This article explains how to add a control to a Windows form from a
Visual Studio add-in.
For windows that contain a Windows Forms designer, the Window.Object property
returns a System.ComponentModel.Design.IDesignerHost object that can be used to
call its CreateComponent method. This method has two overloaded variations: one
of them receives the component type and its name, while the other receives only
the component type and the name is generated automatically. In order to appear
in the form, you must also set the "Parent" property of the new control to the
form (IDesignerHost.RootComponent). To set the property of a control you must
use a PropertyDescriptor, rather than manipulating directly the properties of
the component. The following add-in shows how to do this:
Private m_objDTE As DTE
Public Sub OnConnection(ByVal Application As Object, _
ByVal ConnectMode As Extensibility.ext_ConnectMode, _
ByVal AddInInst As Object, ByRef custom As System.Array) _
Implements Extensibility.IDTExtensibility2.OnConnection
Dim objIDesignerHost As System.ComponentModel.Design.IDesignerHost
Dim objIComponent As System.ComponentModel.IComponent
Dim objPropertyDescriptor As System.ComponentModel.PropertyDescriptor
Try
Select Case ConnectMode
Case ext_ConnectMode.ext_cm_Startup, ext_ConnectMode.ext_cm_AfterStartup
m_objDTE = CType(Application, DTE)
If Not (m_objDTE.ActiveDocument Is Nothing) Then
' Check if the active document window is a Windows Form designer
If TypeOf m_objDTE.ActiveDocument.ActiveWindow.Object Is _
System.ComponentModel.Design.IDesignerHost Then
' Get the Windows Form designer
objIDesignerHost = CType(m_objDTE.ActiveDocument.ActiveWindow.Object, _
System.ComponentModel.Design.IDesignerHost)
' Create the component with a name generated automatically
objIComponent = objIDesignerHost.CreateComponent(GetType(TextBox))
' Set its Parent property
objPropertyDescriptor = System.ComponentModel.TypeDescriptor.GetProperties( _
objIComponent).Item("Parent")
objPropertyDescriptor.SetValue(objIComponent, objIDesignerHost.RootComponent)
End If
End If
End Select
Catch objException As Exception
MessageBox.Show(objException.ToString)
End Try
End Sub
You can code, design, locate code and document your apps much faster using VB.NET, C#, C++ or Visual J#: