Question

I have a VB.net test application that clicks a link that opens the Microsoft Word application window and displays the document. How do I locate the Word application window so that I can grab some text from it?

Was it helpful?

Solution

You can use the Word COM object to open the work document and then you manipulate it. Make sure to add a reference for Microsoft Word first.

Imports System.Runtime.InteropServices
Imports Microsoft.Office.Interop.Word

Public Class Form1

Inherits System.Windows.Forms.Form

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim strFileName As String
Dim wordapp As New Microsoft.Office.Interop.Word.Application
Dim doc As Microsoft.Office.Interop.Word.Document

Try
    doc = wordapp.Documents.Open("c:\testdoc.doc")
    doc.Activate()

Catch ex As COMException

    MessageBox.Show("Error accessing Word document.")

End Try

End Sub

End Class

The doc object is a handle for the instance of Word you have created and you can use all the normal options (save, print etc). You can do likewise with the wordapp. A trick is to use the macro editor in Word to record what you want to do. You can then view this in the Macro Editor. This give you a great starting point for your VB code.

Also, be sure to dispose of the Word COM objects at the end.

OTHER TIPS

I've done something similar with a SourceSafe dialog, which I posted on my blog. Basically, I used either Spy++ or Winspector to find out the window class name, and make Win32 calls to do stuff with the window. I've put the source on my blog: http://harriyott.com/2006/07/sourcesafe-cant-leave-well-alone.aspx

Are you trying to activate the word app? If you want full control, you need to automate word from your vb.net app. Check here for some samples: 1, 2

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top