使用Office互操作获取特定的窗口句柄

Hot*_*otN 6 .net window-handles office-interop

我正在使用Office互操作创建一个新的Word实例:

var word = Microsoft.Office.Interop.Word.Application();
word.Visible = true;
word.Activate;
Run Code Online (Sandbox Code Playgroud)

我可以像这样得到一个窗口句柄:

var wordHandle = Process.GetProcessesByName("winword")[0].MainWindowHandle;
Run Code Online (Sandbox Code Playgroud)

问题是代码的工作原理是假设没有其他Word运行实例.如果有多个,则无法保证它返回的句柄是针对我已启动的实例.我GetForegroundWindow在检测WindowActivate到来自我的对象的事件之后尝试使用但是这一切都在WPF应用程序中运行,该应用程序被设置为作为最顶层的窗口运行,所以我只获得了WPF窗口的句柄.有没有其他方法来获取我的单词实例的句柄?

Edd*_*Paz 6

不知道为什么你需要Word的句柄,但我之前做过的一种方法是实际更改Word窗口标题并搜索它.我这样做是因为我想在控件中托管Word应用程序,但这是另一个故事.:)

  var word = new Microsoft.Office.Interop.Word.Application(); 
  word.Visible = true; 
  word.Activate();
  word.Application.Caption = "My Word";

  foreach( Process p in Process.GetProcessesByName( "winword" ) )
  {
    if( p.MainWindowTitle == "My Word" )
    {
      Debug.WriteLine( p.Handle.ToString() );
    }
  }
Run Code Online (Sandbox Code Playgroud)

获得句柄后,如果愿意,可以恢复标题.