winforms 进程.退出按钮事件异常

u0sqgete  于 2023-06-24  发布在  其他
关注(0)|答案(1)|浏览(119)

密码:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  Button1.Enabled = False
  Dim Process1 As New Process
  Process1.StartInfo.FileName = ("data\test.exe")
  Process1.EnableRaisingEvents = True
  AddHandler Process1.Exited, AddressOf OnExit
  Process1.Start()
End Sub
Sub OnExit(ByVal sender As Object, ByVal e As EventArgs)
  Button1.Enabled = True
End Sub

我试着...

Sub OnExit(ByVal sender As Object, ByVal e As EventArgs)
  Procces1.Close()
  Button1.Enabled = True
End Sub

仍然错误
有什么解决办法吗?

iih3973s

iih3973s1#

由于OnExit是由另一个线程调用的,因此必须使用Control.BeginInvoke Method来修改Button1属性。
您可以从this question (Crossthread operation not valid)使用此Sub来控制Enabled状态:

Private Sub SetControlEnabled(ByVal ctl As Control, ByVal enabled As Boolean)
    If ctl.InvokeRequired Then
        ctl.BeginInvoke(New Action(Of Control, Boolean)(AddressOf SetControlEnabled), ctl, enabled)
    Else
        ctl.Enabled = enabled
    End If
End Sub

更新代码:

Sub OnExit(ByVal sender As Object, ByVal e As EventArgs)
    SetControlEnabled(Button1, True)
End Sub

相关问题