Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
626 views
in Technique[技术] by (71.8m points)

.net - Get specific window handle using Office interop

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;

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...