Another application can be run from a VB.NET program. Using the Shell function, we specify a target executable and any command-line arguments needed.
We learn ways to use the Shell function in practical situations. Shell()
throws exceptions when files are not found, which can be handled in your program as well.
To begin, we specify a target application that happens to be stored in a specific location. You can change the file name to one that exists.
Module Module1 Sub Main() ' Run this specific executable on the shell. ' ... Specify that it is focused. Shell("C:\procexp.exe", AppWinStyle.NormalFocus) End Sub End Module
How can we use Shell to run a command-line program that performs some other action? This example uses the 7-Zip executable program, which performs compression and decompression.
files.7z
.Module Module1 Sub Main() ' Run the 7-Zip console application to compress all txt files ' ... in the C:\ directory. Dim id As Integer = Shell("C:\7za.exe a -t7z C:\files.7z C:\*.txt") Console.WriteLine(id) End Sub End Module1296 7-Zip (A) 9.07 beta Copyright (c) 1999-2009 Igor Pavlov 2009-08-29 [Output truncated]
The Shell function does not work if you only pass the file name you want to open to it. Instead, you need to specify the application you want to open the file with.
Module Module1 Sub Main() ' Use the notepad program to open this txt file. Shell("notepad C:\file.txt", AppWinStyle.NormalFocus) End Sub End Module
The Shell function in the VB.NET language is implemented in managed code but uses lower-level constructs. It is not implemented with the Process type. The 2 types are separate.
The Shell function invokes external processes. The Process type is a more object-oriented approach. But the Shell function is still useful—it is easier to recall and use.