VB.NET: Cannot convert Sender object to Process object. DirectCast and CType fail
Posted on 2003-03-15
I'm new to VB.NET, and I have the following problem: I'm trying to start an external application from a VB.NET program, let's say it's Notepad.exe, and take an action when the external application closes:
I have the following code snippets:
Private WithEvents P As Process
'This procedure works fine, and launches the Notepad without problem
Private Sub btnStartProcess_Click...
P = New Process()
AddHandler P.Exited, AddressOf P_Exited
.EnableRaisingEvents = True
.SynchronizingObject = Me
.StartInfo.FileName = "C:\Notepad.exe"
'This is the event that fires when Notepad closes
Friend Sub P_Exited(ByVal Sender As Object, ByVal e As System.EventArgs)
Dim MyProcess As Process
'This is the line that cuases the problem
MyProcess = DirectCast(Sender, Peocess)
Catch Exc As Exception
When the code in the P_Exited procedure runs, the problem line throws the exception #13 'Specified Cast is not valid'. If Process object is the one that raised this event, why Sender (As Object) cannot be converted to Process object?
I also was trying CType instead of DirectCast with the same result.