I create a WordDocument project named WordDocumentTest in VSTO follow the steps in Create the project and a WPF project named WpfAppRunInVSTO.
Step 1: Add WpfAppRunInVSTO as reference in WordDocumentTest
Step 2: Add below references: PresentationCore,PresentationFramework,WindowsBase to WordDocumentTest
Step 3: Add a button in the Document with a Click event
Step 4: The code for ThisDocument
public partial class ThisDocument
{
private void ThisDocument_Startup(object sender, System.EventArgs e)
{
this.Paragraphs[2].Range.InsertParagraphAfter();
this.Paragraphs[3].Range.Text = "This text was added by using code.";
this.Paragraphs[3].Range.Bold = 50;
this.Paragraphs[3].Range.InsertParagraphAfter();
this.Paragraphs[4].Range.InsertDateTime();
}
private void ThisDocument_Shutdown(object sender, System.EventArgs e)
{
}
#region VSTO Designer generated code
private void InternalStartup()
{
this.button1.Click += new System.EventHandler(this.button1_Click);
this.Startup += new System.EventHandler(this.ThisDocument_Startup);
this.Shutdown += new System.EventHandler(this.ThisDocument_Shutdown);
}
#endregion
private void button1_Click(object sender, EventArgs e)
{
var t = new Thread(() =>
{
MainWindow window = new MainWindow();
window.Closed += (s2, e2) => window.Dispatcher.InvokeShutdown();
window.Show();
System.Windows.Threading.Dispatcher.Run();
});
t.SetApartmentState(ApartmentState.STA);
t.Start();
}
The result picture as below shown:
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.