在word Com加载项的时候,新建的Form窗体成为Word窗口的子窗体。
using System;
using Word = Microsoft.Office.Interop.Word;
using System.Runtime.InteropServices;
namespace TestWordAddin1
{
public partial class ThisAddIn
{
/// <summary>
/// 指定一个窗口的新父
/// </summary>
/// <param name="hWndChild">子窗口的句柄</param>
/// <param name="hWndNewParent">新父窗口的句柄</param>
/// <returns></returns>
[DllImport("user32.dll", EntryPoint = "SetParent")]
public static extern int SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
/// <summary>
/// 获得活动窗口的句柄
/// </summary>
/// <returns></returns>
[DllImport("user32.dll", EntryPoint = "GetActiveWindow")]
public static extern int GetActiveWindow();
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
//将Form窗体设置为Word窗口的子窗体
SetNewParentWindow();
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}
/// <summary>
/// 将Form窗体设置为Word窗口的子窗体
/// </summary>
private void SetNewParentWindow()
{
//获取当前Word文档对象
Word.Application wordapp = Globals.ThisAddIn.Application;
//API函数返回Word窗口的句柄 (1)先获取Word窗体句柄
int WordHwnd = GetActiveWindow();
IntPtr wordHwnd = new IntPtr(WordHwnd);//转化
//实例化Form窗口 (2)再获取Form窗口的句柄
Form1 self = new Form1();
self.Show();
//通过API函数SetParent 设置父子窗体
//SetParent(子窗体的句柄,父窗体的句柄)
SetParent(self.Handle, wordHwnd);
}
#region VSTO 生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要修改
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
}
#endregion
}
}
运行效果图: