Recipe 14.5. Waiting for Applications to Finish


Problem

You need to start up a separate application. Once it starts, you need to wait until that program completes. Your application can then continue on with its own processing.

Solution

Use the System.Diagnostics. Process.Start() method to initiate the program and return an instance of System.Diagnostics.Process. Now call that object's WaitForExit() method.

Recipe 14.4 discusses how to use the Start() method, so we won't repeat all that detail here. The following code starts up Notepad and waits for it to exit before continuing:

 Dim notepadProcess = Process.Start("Notepad.exe") notepadProcess.  WaitForExit( ) MsgBox("Welcome back!") 

Discussion

The WaitForExit() method accepts an optional millisecond count as its only argument. When used, WaitForExit() waits up to the number of milliseconds specified and then continues with the program, even if the external process is still running.

Another Process class method, WaitForInputIdle(), waits until the external process has reached a state where it is waiting for user input before continuing. It also accepts an optional millisecond count.

As discussed in Recipe 14.4, you can also use the Visual Basic Shell() function to start applications. This function includes two optional arguments (the third and fourth arguments) that control how long the current program should wait for the external process. The third argument, wait, accepts a Boolean value that, when set to true, causes the current program to wait until the external program completes. The fourth argument, timeout, indicates the maximum time, in milliseconds, that the program should wait for the external program to complete before continuing. Its default value is -1, which causes Shell() to wait forever.

The following statement starts up Notepad and waits up to 10 seconds for it to complete:

 Shell("Notepad.exe", AppWinStyle.NormalFocus, True, 10000) 

See Also

Recipe 14.4 discusses the Shell() function and the Process.Start() method.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net