使用被调用函数在visual basic 2010中调用计时器?

时间:2012-07-29 22:24:26

标签: vb.net visual-studio-2010 function timer

我想知道是否有办法通过函数调用计时器。此函数本身通过自动计时器调用,该计时器在表单加载时激活。

Function callTimer(ByRef var1 As Integer, ByVal var2 As Integer)
    'statements()
    Media.SystemSounds.Beep.Play() 'to ensure that it is called
    Call otherFunction(ByRef var3 As Integer) <-- how do you do this??
    Return var1
End Function

我想知道如何做到这一点。当我尝试这样或类似的东西时,VB给了我一个错误。

全部谢谢!

2 个答案:

答案 0 :(得分:1)

问题是您正在定义方法参数,而不是设置它们。

您需要传递一个值,例如:

Call otherFunction(var2) 

答案 1 :(得分:0)

@competent_tech所说的是你在函数中定义一个函数,这是非法的。您想要调用该功能,而不是定义它。这样的一个例子是这样的:

Shared _timer As Timer 'this is the timer control

Function callTimer(ByRef var1 As Integer, ByVal var2 As Integer)
    Media.SystemSounds.Beep.Play() 'to ensure that it is called
    Dim testInt As Integer
    testInt = 4
    Call otherFunction(testInt) '<-- this calls otherFunction and passes testInt
    Return var1
End Function

Function otherFunction(ByRef var3 As Integer)
    StartTimer(var3) ' this will start the timer and set when the timer ticks in ms
                ' (e.g. 1000ms = 1 second)
End Function

'this starts the timer and adds a handler. The handler gets called every time 
'the timer ticks
Shared Sub StartTimer(ByVal tickTimeInMilliseconds As Integer)
    _timer = New Timer(tickTimeInMilliseconds)
    AddHandler _timer.Elapsed, New ElapsedEventHandler(AddressOf Handler)
    _timer.Enabled = True
End Sub
'this is the handler that gets called every time the timer ticks
Shared Sub Handler(ByVal sender As Object, ByVal e As ElapsedEventArgs)
    ' . . . your custom code here to be called every time the timer tickets
End Sub

看起来你可能会对调用函数与定义函数有点混淆。在使用函数之前,必须先定义它,就像上面的示例代码一样。

要更好地处理的另一件事是使用 ByRef ByVal 。 ByRef将引用传递给内存中的地址。这意味着函数中变量的任何更改都将保留在函数之外。但是,ByVal不会在函数之外持久存在,并且传递给函数之前的值将与函数调用之后的值相同。这是一个例子:

Sub Main()
    Dim value As Integer = 1

    ' The integer value doesn't change here when passed ByVal.
    Example1(value)
    Console.WriteLine(value)

    ' The integer value DOES change when passed ByRef.
    Example2(value)
    Console.WriteLine(value)
End Sub

'any Integer variable passed through here will leave unchanged
Sub Example1(ByVal test As Integer)
    test = 10
End Sub

'any Integer variable passed through here will leave with a value of 10
Sub Example2(ByRef test As Integer)
    test = 10
End Sub

<强>结果:

  

test = 1

     

test = 10

可以看到此ByRef / ByVal示例at this link。如果你仍然感到困惑,那就值得深入了解。

编辑:此修改包含有关invoking a timer in VB.NET的信息。