如何在VB.NET代码中触发事件?

19

我有一个表单,其中包含一个开始按钮(允许用户重复运行进程),我希望在表单加载时发送btnStart.Click事件,以便自动启动流程。

我有以下函数处理btnStart.Click事件,但我该如何告诉Visual Basic“假装有人点击了这个按钮并触发这个事件”呢?

我试着写得非常简单,基本上是可行的。然而,Visual Studio 给出了警告Variable 'sender' is used before it has been assigned a value,因此我猜这不是正确的方法:

```vb Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click 'Code for starting processes goes here. End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Code to fire the btnStart.Click event goes here. btnStart_Click(Nothing, Nothing) End Sub ```
Dim sender As Object
btnStart_Click(sender, New EventArgs())

我也尝试使用 RaiseEvent btnStart.Click,但是会出现以下错误:

'btnStart' 不是 'MyProject.MyFormClass' 的事件。

代码

Imports System.ComponentModel

Partial Public Class frmProgress

    Private bw As BackgroundWorker = New BackgroundWorker

    Public Sub New()

        InitializeComponent()

        ' Set up the BackgroundWorker
        bw.WorkerReportsProgress = True
        bw.WorkerSupportsCancellation = True
        AddHandler bw.DoWork, AddressOf bw_DoWork
        AddHandler bw.ProgressChanged, AddressOf bw_ProgressChanged
        AddHandler bw.RunWorkerCompleted, AddressOf bw_RunWorkerCompleted

        ' Fire the 'btnStart.click' event when the form loads
        Dim sender As Object
        btnStart_Click(sender, New EventArgs())

    End Sub

    Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click

        If Not bw.IsBusy = True Then

            ' Enable the 'More >>' button on the form, as there will now be details for users to view
            Me.btnMore.Enabled = True

            ' Update the form control settings so that they correctly formatted when the processing starts
            set_form_on_start()

            bw.RunWorkerAsync()

        End If

    End Sub

    ' Other functions exist here

End Class
5个回答

28
你应该将一个名为sender的按钮作为事件处理程序发送:
btnStart_Click(btnStart, New EventArgs())

11

涉及到引发事件的步骤如下:

Public Event ForceManualStep As EventHandler
RaiseEvent ForceManualStep(Me, EventArgs.Empty)
AddHandler ForceManualStep, AddressOf ManualStepCompletion

Private Sub ManualStepCompletion(sender As Object, e As EventArgs)        


End Sub

所以在您的情况下,应该如下所示:

btnStart_Click(btnStart, EventArgs.Empty)

7

仅需一通电话

btnStart.PerformClick()

6

你试图实现一种不好的想法。实际上,你需要创建一个子例程来完成这些任务。

Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click

      call SeparateSubroutine()

End Sub

private sub SeparateSubroutine()

   'Your code here.

End Sub

然后无论在哪里调用 btnStart 的点击事件,只需要调用该 SeparateSubroutine 即可。这应该是您情况下的正确方式。


1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接