使用Office互操作获取特定的窗口句柄 [英] Get specific window handle using Office interop

查看:121
本文介绍了使用Office互操作获取特定的窗口句柄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过执行以下操作使用Office互操作创建Word的新实例:

I'm creating a new instance of Word using the Office interop by doing this:

var word = Microsoft.Office.Interop.Word.Application();
word.Visible = true;
word.Activate;

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

I can get a window handle like this:

var wordHandle = Process.GetProcessesByName("winword")[0].MainWindowHandle;

问题在于代码在没有其他Word实例运行的假设下工作.如果有多个,则不能保证它返回的句柄是针对我启动的实例的.在从对象中检测到WindowActivate事件后,我尝试使用GetForegroundWindow,但这都是在WPF应用程序中运行的,WPF应用程序设置为作为最顶层的窗口运行,因此我只是获得WPF窗口的句柄.还有其他方法可以获取我的word实例的句柄吗?

The problem is that code works on the assumption that there's no other instance of Word running. If there are multiple, it can't guarantee that the handle it returns is for the instance that I've launched. I've tried using GetForegroundWindow after detecting a WindowActivate event from my object but this is all running within a WPF application that's set to run as the topmost window, so I just get the handle to the WPF window. Are there any other ways to get the handle for my instance of word?

推荐答案

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

Not sure why you need the handle to Word, but one way I've done this before is to actually change the Word window caption and search for it. I did this because I wanted to host the Word application inside a control, but that's another story. :)

  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() );
    }
  }

一旦有了手柄,就可以根据需要恢复字幕.

Once you got the handle, you can restore the caption if you like.

这篇关于使用Office互操作获取特定的窗口句柄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆