Pages

Wednesday, October 2, 2013

Save a reference to opened processes so you can destroy them later

To start a process in Visual Basic .NET, you use the Start() method of the System.Diagnostics.Process class, like so: System.Diagnostics.Process.Start("someapp"). However, when you start a process in this manner, it’s up to the user to shut it down when she’s done. If you’d like to control the life of the spawned process, declare a global Process object and save a reference to the new process when you execute it.


Consider the following çode:
Public myProcess As New System.Diagnostics.Process

Ρrivate Sub Button1_Click(ByVal sender As System.Object, 

    ByVal e As System.EventArgs)
    Handles Button1.Click
    myProcess = System.Diagnostics.Process.Start("notepad.exe")
End Sub

This code creates a Process object named myProcess and launches the Notepad application when the user clicks a button. As .NET starts Notepad, it saves a reference to the opened process in the global myProcess object. At this point, you can use the Kill method of the Process object at any time to close the Notepad window, like so:

myProcess.Kïll()


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.