Using the Process Class
Less frequently now I venture back to VB6 to help someone or work on an existing application. Naturally I try to use some aspect of .NET and am quickly reminded of how much easier things have become in .NET. One such convenience is the Process class. The Process class facilitates spawning a new process. VB6 has the convenient Shell command, or we can use one of the API methods like WinExec for extended control, but comparatively the Process class seems tighter and more powerful.
Suppose we want to add a Tools menu to the Calculator application during debugging to facilitate examining the Trace information sent to the custom event log (refer to the earlier section Logging Application Events.) We could use the Process class to spawn an instance of the Event Viewer. This is much easier than remembering the forgettable eventvwr.msc/s command prompt trick. To demonstrate I added a ToolsView Event Log menu item to our chapter sample application. In the event handler for the menu's Click event I can invoke a named method, ShowEventViewer , that spawns the Event Viewer by using the Process.Start shared method. Listing 17.11 demonstrates how to start the external process.
Listing 17.11 Starting an External Application by Using the Process.Start Shared Method
Private Sub ShowEventViewer() Process.Start(Environment.SystemDirectory + "\eventvwr.msc", "/s") End Sub Private Sub MenuItem9_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MenuItem9.Click ShowEventViewer() End Sub
The Click event for MenuItem9 calls a named event. You could provide a more meaningful name for the menu, or as an alternative you could simply call a well-named method, which both facilitates comprehension and promotes reuse in a way a better menu item name won't.
The ShowEventViewer method calls the shared method Process. Start , passing the name of the process to start and arguments to that application. You could do something similar in VB6 with Shell ; however, I find it especially convenient to be able to get the system directory ”usually C:\winnt\system32 ”with the shared, read-only property Environment. SystemDirectory . All I have to do is concatenate the application (or file) to spawn. Clearly you could simply hard-code the C:\winnt\system32\ eventvwr.msc path and filename and be right 95 percent of the time, but dynamically coding the path is better. And with VB .NET you don't have to remember which API to call to get environment variables or the system directory; this information is provided in a class. Very nice.
This kind of collective convenience promotes hyper-productivity. The .NET Framework is providing routine housekeeping for us so we can focus on solving new problems. (It would be great if we could simplify the keyboard in a like manner.)