[Net] VB. NET starts and monitors external programs

Source: Internet
Author: User

You no longer need to use Win32 application programming interfaces or vB Shell functions to start external applications. Because you can use the system. Diagnostics. Process class in the. NET Framework to further simplify the code. Although. Net makes a lot of things more complex, it is not here to start external applications. In traditional vbprograms, you can use shell functions to start an application. When you transfer a data file name, VB opens the data file in the corresponding application. You can use any windowstyle parameter to control the window mode of the started application.

For example, in VB6, the following line of code starts the default text editor (usually notepad) and opens the file "C:/somepath/somefile.txt": returnid = shell ("C: /somepath/somefile.txt ", vbnormalfocus ).

Through Microsoft. VisualBasic. comaptibility Domain Name Space, the shell function can still be used in VB. NET, and it has been modified.

However. in the. NET Framework, it is not the best way to start an application, because Shell functions have some strict restrictions, one of which is to start the program asynchronously. After the application is started, your own program will continue to run. Therefore, you cannot use it directly to start a program, and you can only return to your own program after the program exits.

To do this in traditional VB, you must turn to the Windows API, which requires you to understand the window handle, process identification number, and enumeration top level window. Using. Net makes this operation very simple. You can use the process class in the system. Diagnostics Domain Name Space to start external programs. You can simply use the shared process. Start method to start a new process and transmit an executable file name or an extended associated file name of the executable application to it as a parameter.

For example, the following code starts the "C:/somepath/somefile.txt" file. System. Diagnostics. process. Start ("C:/somepath/somefile.txt ")

The start method has an overloaded version and can return a process object. Therefore, you can obtain a reference to the startup process and use it for multiple purposes: dim myprocess as process = system. diagnostics. process. start ("C:/somepath/somefile.txt") MessageBox. show (myprocess. processname)

At first glance, you seem to have lost the ability to control the window style (remember the second parameter of the shell function ?), However, this is not the case. In many cases, you do not need to explicitly set the window style, because it is started in a normal window with focus (processwindowstyle. Normal) by default. However, if you want to use a different window style, you can use the overloaded process. Start method to receive a processstartinfo object parameter instead of a simple string. To use it, you must first create a processstartinfo object and then set the initial process value. Two overload methods allow you to set a file name, a file name, and a group of command line parameters. The processstartinfo object also has a windowstyle attribute, which consists of the system. Diagnostics. process. windowstyle enumerated values. Therefore, you can call the process. Start method and send a processstartinfo object to control the style of the window to be started.

Dim psinfo as new _ system. Diagnostics. processstartinfo _ ("C:/somepath/somefile.txt ")

Psinfo. windowstyle = _ system. Diagnostics. processwindowstyle. Normal

Dim myprocess as process = _ system. Diagnostics. process. Start (psinfo)

Because the process class has a startinfo attribute and is a processstartinfo object, another way to produce the same result is to create a process object and set its startinfo attribute.

You can only call the start method of a pre-created process object without using the shared start method of the Process class.

Dim myprocess as system. Diagnostics. Process = _ new system. Diagnostics. Process ()

Myprocess. startinfo. filename = _ "C:/somepath/somefile.txt"

Myprocess. startinfo. windowstyle = _ system. Diagnostics. processwindowstyle. Normal myprocess. Start sets the process parameter during design.

The. NET Framework comes with a process component that encapsulates the code during design. You can find the component in the toolbar. To use it, drag a process component to your form and expand the startinfo attribute in the Properties window. You can add a process component to a form so that you can set properties during design rather than during running.

Monitor Startup Process

So far, you have seen that the startup process uses an Asynchronous Method, just like the traditional VB shell function. In other words, after the process is started, the code in the parent program can continue to be executed. You need some methods to monitor the startup process and find out when they exit or whether they are still running. Depending on your application, you may need to use different methods to handle this problem. Start the process and stop your program until it exits.

Start the process, monitor it, and do something only when it ends, and make your program run normally.

Start the process, give it some input, let it process the input, and then force it to exit.

Start the process, and execute some operations as long as the startup process is running or there is no problem during the running process. If the process exits or stops, you need to take some actions.

Start the process, and give it some special input, and/or obtain the output results produced by further processing.

For example, you may want to start a command window, input some content in this window programmatically, and then obtain and process the output results. Start a process and wait until it exits

Call the process. waitforexit method when you wait for the simplest method for the end of a startup process. This causes the running of the starting process to stop until the started process exits. Unfortunately, when you use this method directly from a Windows form, it can also cause the form to stop responding to system events, such as painting.

So in general, you don't want to start an external program using the waitforexit method from a button (although the waitforexit method is very suitable for starting another process from an application without a visual user interface, for example, from an ASP.. NET application server to call the console application ). Let you see what will happen when using this method from a form.

Private sub btnwaitforexit_click (_ byval sender as system. Object, _ byval e as system. eventargs) _ handles btnwaitforexit. click' creates a new process

Dim myprocess as process = _ system. Diagnostics. process. Start ("sample.txt") 'Wait until it exits myprocess. waitforexit ()'

Display result

MessageBox. Show ("Notepad was closed :"&_

Myprocess. exittime &"."&_

System. environment. newline & "Exit Code:" & _ myprocess. exitcode)

Myprocess. Close ()

End sub

The previous example shows an interesting situation. Even after the process is started, you still have the ability to access the process object in the Code. However, in this case, most process attributes are unavailable because the process itself does not exist. You can still read the exitcode and exittime attributes. These two attributes return integer and datetime values respectively. The doscommand sets an exit code to let you know if an error has occurred .. Net and other Windows applications can set this value by using the return value of the main method. By default, this value is equal to zero. For a DOS command, a non-zero exitcode value either indicates an error or indicates that the command process is aborted abnormally.

Start an invisible process

In a visible window, you don't have to start a process. Sometimes you just want to run a process and get the output value. The following example converts the current directory to a system directory, and then runs a DOS dir command "*. com "parameter to list all directories. COM file extension. In Windows XP, the shell interpreter recognizes the "&" operator as a command separator, so you can place multiple commands in one line. ">" The operator redirects the output value to a specific file. In this case, the Code imports the results displayed by DIA into the "diroutput.txt" file in the path specified by the application. startuppath attribute.

Dim myprocess as process = new process ()

Dim s as string

Dim OUTFILE as string = application. startuppath & _ "/diroutput.txt" 'to obtain the system path

Dim sysfolder as string = _ system. environment. getfolderpath _ (environment. specialfolder. System) 'sets the file name and command line parameters

Myprocess. startinfo. filename = "cmd.exe" myprocess. startinfo. Arguments = "/c Cd "&_

Sysfolder & "& dir *. com>" & CHR (34 )&_

OUTFILE & CHR (34) & "& Exit" 'starts in a hidden window

Myprocess. startinfo. windowstyle = _ processwindowstyle. Hidden

Myprocess. startinfo. createnowindow = true myprocess. Start ()

'If the process cannot be completed within 1 second, destroy it

Myprocess. waitforexit (1000)

If not myprocess. hasexited

Then myprocess. Kill ()

End if

'Display the exit time and exit code

MessageBox. show ("The 'dir' command window was" & _] "closed at:" & myprocess. exittime &". "& _ system. environment. newline & "Exit Code:" & _ myprocess. exitcode)

Myprocess. Close ()

The previous Code returns a zero (0) exitcode. If you want to see an example of exitcode with a non-zero value, you can add an "X" or another character to the system directory to make it illegal. This leads to an error. The exitcode value will be different. Because a process with errors may run continuously, the Code waits for several milliseconds by using an overloaded waitforexit method before returning to the program that controls startup. The above code waits for one second, then calls the kill method to end the startup process, and forces the process to exit. Check whether diroutput.txt exists in your application startup directory. Test when a process exits

In VB6, you can call the getmoduleusage () function of Win32 API to determine when the process ends. In.. net, the corresponding operation is continuously loop after the startup process, check the process. hasexited property and application. the doevents method processes other events in your application until the process ends. Do while not myprocess. hasexited application. doevents loop but the process class gives you a more concise method to determine when the process exits-it can generate an exited event. To make this happen, you need to set the process. enableraisingevents attribute to true (the default attribute value is false) and create an event handle. For example, 'Allow process generation event myprocess. enableraisingevents = true' adds an exited event handle.

Addhandler myprocess. exited, _ addressof me. processexited

'Start the process

Myprocess. Start ()

'Event handlers

Friend sub processexited (byval sender as object, _ byval e as system. eventargs)

Dim myprocess as process = directcast (_ sender, process)

MessageBox. Show ("the process exited, raising "&_

"The exited event at:" & myprocess. exittime &_

"." & System. environment. newline &_

"Exit Code:" & myprocess. exitcode)

Myprocess. Close ()

End sub

The potential problem with using these two methods is that if the startup process is suspended or never exits, your application will stop. The solution is to add a timer to periodically check whether the started program has a response. Sometimes, you may not only want to use simple command lines, but want to directly send more complex input information to the startup process. The method used in the previous example to import the output to a file is not always the best choice. In many cases, importing the output directly back to your application may be more effective. For programs that use stdin, stdout, and stderr, such as console applications, You can override the default method, provide a streamwriter for input, and provide a streamreaders for reading stdout and stderr output values. When starting the process, you must set the redirectstandardinput, redirectstandardoutput, and redirectstandarderror attributes of the processstartinfo object to true. After the process is started, use the standardinput, standardoutput, and standarderror attributes of the Process object to allocate the input and output streams to the streamreader and streamwriter objects. Warning: by default, the framework uses the Win32 ShellExecute Function to start the process internally. However, to reallocate the input and output streams, you must set processstartinfo before starting the process. the useshellexecute attribute is false. Note that when you do this, you must either specify the full path to the file, or the file location must be in the Environment path.

For example, the following code creates an invisible window, obtains the directory list of The. com file in the system directory, and then displays the result in a message box. Dim myprocess as process = new process ()

Dim s as string myprocess. startinfo. filename = "cmd.exe"

Myprocess. startinfo. useshellexecute = false

Myprocess. startinfo. createnowindow = true

Myprocess. startinfo. redirectstandardinput = true

Myprocess. startinfo. redirectstandardoutput = true

Myprocess. startinfo. redirectstandarderror = true

Myprocess. Start () dim sin as streamwriter = myprocess. standardinput

Sin. autoflush = true

Dim sout as streamreader = myprocess. standardoutput

Dim serr as streamreader = myprocess. standarderror

Sin. Write ("dir C:/Windows/system32/*. com "&_

System. environment. newline)

Sin. Write ("exit" & system. environment. newline)

S = sout. readtoend ()

If not myprocess. hasexited then

Myprocess. Kill ()

End if

MessageBox. Show ("The 'dir' command window was "&_

Closed at: "& myprocess. exittime &"."&_

System. environment. newline & "Exit Code :"&_

Myprocess. exitcode)

Sin. Close ()

Sout. Close ()

Serr. Close ()

Myprocess. Close ()

MessageBox. Show (s)

For programs that do not use stdin, you can use the sendkeys method to input key events.

For example, the following code starts notepad and enters some text.

Dim myprocess as process = new process ()

Myprocess. startinfo. filename = "Notepad"

Myprocess. startinfo. windowstyle = _ processwindowstyle. Normal

Myprocess. enableraisingevents = true

Addhandler myprocess. exited, _ addressof me. sendkeystestexited

Myprocess. Start ()

Myprocess. waitforinputidle (1000)

If myprocess. Responding then

System. Windows. Forms. sendkeys. sendwait (_ "this text was entered using "&_

"System. Windows. Forms. sendkeys method .")

Else

Myprocess. Kill ()

End if

You can use the sendkeys method to send any input values, including the ALT, Ctrl, and shift keys. Therefore, you can use it to save or load files, exit, or execute other menu-driven commands. However, the sendkeys method only sends the input value to the activity window (that is, the window with focus). Therefore, if an application loses focus during this process, problems may occur.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.