How can I add a managed control onto the document surface in an Add-in?
Locked
-
Sunday, February 08, 2009 12:43 PMModerator
How can I add a managed control onto the document surface in an Add-in?
Please remember to mark the replies as answers if they help and unmark them if they provide no help.- Edited by Ji.ZhouModerator Saturday, February 14, 2009 1:19 AM
All Replies
-
Sunday, February 08, 2009 12:43 PMModerator
Before Visual Studio 2008 SP1, we can only add a managed control onto the Office document in a document level project. With the Visual Studio 2008 SP1, we can achieve the same objective for the application level project now.
The core is that VSTO has exported a method named GetVstoObject() from the class DocumentExtensions in the Microsoft.Office.Tools.Word.Extensions namespace. This is an extension method that can be called from a native Word document. The method GetVstoObject() will return a VSTO wrapped document. We can then call Microsoft.Office.Tools.Word.Document.Controls.Add() to place a managed control onto the document surface.
The following sample codes add a button onto a Word document in the Add-in startup:
private Button btn = null;
private Microsoft.Office.Tools.Word.Document doc = null;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
doc = this.Application.ActiveDocument.GetVstoObject();
btn = doc.Controls.AddButton(0, 0, 50, 20, "MyButton");
btn.Click += new EventHandler(btn_Click);
btn.Text = "My Button";
}
void btn_Click(object sender, EventArgs e)
{
MessageBox.Show("This is a managed button in Word Add-in project");
}
(Related forum thread, http://social.msdn.microsoft.com/Forums/en-US/vsto/thread/37c49ef4-8ca7-4874-b82c-f8f170daf08a/ )
For more FAQ about Visual Studio Tools for Office, please see Visual Studio Tools for Office FAQ
Please remember to mark the replies as answers if they help and unmark them if they provide no help.- Marked As Answer by Ji.ZhouModerator Wednesday, February 11, 2009 12:49 PM
-
Wednesday, April 01, 2009 12:02 PMModerator
Add VB version codes,
Private btn As Button
Private doc As Microsoft.Office.Tools.Word.DocumentPrivate Sub ThisAddIn_Startup(ByVal sender As Object, ByVal e As System.EventArgs)
doc = Me.Application.ActiveDocument.GetVstoObject()
btn = doc.Controls.AddButton(0, 0, 50, 20, "MyButton")
AddHandler btn.Click, AddressOf btn_Click
btn.Text = "My Button"
End SubSub btn_Click(ByVal sender As Object, ByVal e As EventArgs)
MessageBox.Show("This is a managed button in Word Add-in project")
End Sub
We have published a VSTO FAQ recently, you can view them from the entry thread http://social.msdn.microsoft.com/Forums/en/vsto/thread/31b1ffbf-117b-4e8f-ad38-71614437df59. If you have any feedbacks or suggestions on this FAQ, please feel free to write us emails to colbertz@microsoft.com.

