1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| Imports System.Diagnostics
Imports System.Threading.Tasks
' Colle ce Sub dans la classe Form1.
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim proc As Process = Nothing
Try
Dim startInfo As New ProcessStartInfo("cmd.exe") With {
.UseShellExecute = True
}
proc = Process.Start(startInfo)
If proc Is Nothing Then
MessageBox.Show("Impossible de démarrer cmd.exe", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error)
Return
End If
' Attendre 5 secondes
Await Task.Delay(5000)
' Tenter une fermeture propre
If Not proc.HasExited Then
Try
proc.CloseMainWindow()
' attendre 2s pour la fermeture propre
If Not proc.WaitForExit(2000) Then
' forcer la terminaison (inclut l'arbre si supporté)
Try
proc.Kill(entireProcessTree:=True)
Catch exKill As Exception
' fallback si la surcharge n'est pas disponible
If Not proc.HasExited Then proc.Kill()
End Try
End If
Catch ex As Exception
' en dernier recours, forcer la terminaison
Try
If Not proc.HasExited Then proc.Kill()
Catch
End Try
End Try
End If
Finally
If proc IsNot Nothing Then
proc.Dispose()
End If
End Try
End Sub |