18

我有一个带有开始按钮的表单(允许用户根据需要反复运行进程),并且我想btnStart.Click在表单加载时发送一个事件,以便进程自动启动。

我有以下btnStart.Click事件功能,但我如何真正告诉 Visual Basic '假装有人点击了按钮并触发此事件'?

我试过很简单,这基本上是有效的。但是,Visual Studio 给了我一个警告Variable 'sender' is used before it has been assigned a value,所以我猜这不是真正的方法:

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
4

5 回答 5

26

您应该将按钮发送sender到事件处理程序中:

btnStart_Click(btnStart, New EventArgs())
于 2013-04-05T10:36:55.993 回答
10

参与引发事件的步骤如下,

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)
于 2013-04-05T10:50:06.270 回答
6

打电话

btnStart.PerformClick()
于 2013-04-05T10:48:39.787 回答
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's click event,就调用那个SeparateSubroutine。在您的情况下,这应该是正确的方法。

于 2013-04-05T11:03:14.437 回答
0

您可以将按钮子类化并OnClick公开其方法,如我在此处所述

于 2021-08-09T09:59:35.840 回答