vb.netms-wordoffice-interopwindow-handles

ActiveDocument.ActiveWindow.Hwnd crash


I'm using ActiveDocument.ActiveWindow.Hwnd to get the handle of the active document Window in MS Word, but it does crash in Word 2007. I tried using long instead of int, tried to catch the exception but no exception is thrown.

Public WithEvents wa As Microsoft.Office.Interop.Word.Application
wa = HostApplication

    Public Function getWindowHWND() As Integer
        Try
            getWindowHWND = wa.ActiveDocument.ActiveWindow.Hwnd
        Catch ex As Exception
            MsgBox(1)
            getWindowHWND = -1
        Finally
        End Try
    End Function

Am I doing something wrong? Is this a bug? How can I get the handle in an equivalent way if it's not fixable? Thank you in advance.


Solution

  • No such property exist in Word 2007.

    Since Word 2013 you could use the Hwnd property of Window that is exposed from the Application object:

    var windowHandle = wordApplication.ActiveWindow.Hwnd;
    

    There is no need to use the ActiveDocument property in the middle. This fails when no document is open.

    In earlier Word versions you could use the Process class from the .NET BCL to retrieve the main window handle, for example:

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