问题
I am working on an application that needs to launch Microsoft Word, and then resume when the user closes Word. The code below should work, but it does not. I get an 'object not set to an instance of an object'
1 Dim pInfo As New ProcessStartInfo
2 Dim P As New Process
3 pInfo.FileName = "C:\test\LLR.doc"
4 P = Process.Start(pInfo)
5 ''# Here is where it goes bad
6 P.WaitForInputIdle()
7 P.WaitForExit()
I put p
into the watch window and it shows a a system.diagnostics.process
in the watch after line2, but after line 4 it return to NOTHING. The process launches, but I can not monitor it any longer with lines 6 & 7. Is this a 'limitation' of Visual Studio 2010 or am I making an operator error? The MS Help does not show process available in the 2010 version (it is in Visual Studio 2005 and Visual Studio 2008).
--Edit based on feedback - final solution
Private Function StartWord(ByVal NewFileName As String) As Boolean
MessageBox.Show("When you have finished editing the report, save and close word to complete operation")
Dim wapp As Application
wapp = New Microsoft.Office.Interop.Word.Application
wapp.Documents.Open(NewFileName)
wapp.Visible = True
wapp.WindowState = WdWindowState.wdWindowStateMaximize
wapp.Caption = "Large Loss Report"
Try
While wapp.Documents.Count > 0
System.Windows.Forms.Application.DoEvents()
End While
wapp.Quit()
Catch ex As Exception
End Try
Return True
End Function
回答1:
Microsoft Word is a Big Program. Running several copies of it would quickly make the average consumer level machine keel over. To avoid this, Word makes sure that only one instance ever runs, taking care of all documents. A so-called single-instance app.
So if you start Word like you do and Word is already running then the 2nd copy you start only asks the 1st instance to open the document. And immediately exits. Making your code bomb. This also stops you from doing what you are trying to do, you cannot tell when the user closes the 2nd document, only when she closes all documents. One imperfect workaround would be to try to open the .doc file periodically. It is locked as long as Word has it opened.
来源:https://stackoverflow.com/questions/5249852/launch-and-watch-a-process-from-vb-net-2010