vb.net Visual Basic 的基本延迟命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17615633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 16:59:42  来源:igfitidea点击:

Basic delay command for Visual Basic

vb.netvisual-studio

提问by Brandon Nguyen

I need a wait command in Visual Basic that suits me.

我需要一个适合我的 Visual Basic 中的等待命令。

I know:

我知道:

Declare Sub Sleep Lib "kernel32.dll" (ByVal milliseconds As Long)
sleep 5000

But that makes the program unresponsive.

但这会使程序无响应。

System.Threading.Thread.Sleep(5000) 'The window doesn't load until the timing is over (useless)

My code:

我的代码:

Imports Microsoft.Win32 'To check if is 64Bit or 32Bit

Public Class Loading
  Private Sub Loading_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    If Registry.LocalMachine.OpenSubKey("Hardware\Description\System\CentralProcessor
1. function 'OnInitialize' cannot be declared 'Overrides' because it does not override a function in a base class.
2.  'MinimumSplashScreenDisplayTime' is not a member of 'App.Loading.MyApplication'.
    3.  'OnInitialize' is not a member of 'Object'.
").GetValue("Identifier").ToString.Contains("x86") Then My.Settings.Is64 = False Else My.Settings.Is64 = True End If 'I need command here If My.Settings.Is64 = True Then Form64.Show() Me.Close() Else MsgBox("No version developed for 32-bit computers.") End End If End Sub End Class

Errors:

错误:

@Idle_Mind

@Idle_Mind

Namespace My

    ' The following events are available for MyApplication:
    ' 
    ' Startup: Raised when the application starts, before the startup form is created.
    ' Shutdown: Raised after all application forms are closed.  This event is not raised if the application terminates abnormally.
    ' UnhandledException: Raised if the application encounters an unhandled exception.
    ' StartupNextInstance: Raised when launching a single-instance application and the application is already active. 
    ' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected.
    Partial Friend Class MyApplication

        Protected Overrides Function OnInitialize(ByVal commandLineArgs As System.Collections.ObjectModel.ReadOnlyCollection(Of String)) As Boolean
            ' Set the display time to 5000 milliseconds (5 seconds). 
            Me.MinimumSplashScreenDisplayTime = 5000
            Return MyBase.OnInitialize(commandLineArgs)
        End Function

    End Class


End Namespace

回答by Idle_Mind

Are you trying to implement a splash screen? --> @ChrisDunaway Yes, I'm doing a splash screen.

您是否正在尝试实现启动画面?--> @ChrisDunaway 是的,我正在做一个启动画面。

Go into Project Properties and leave your main form as the Startup form. Set your splash screen form as the splash screen entry down at the bottom. Now click the "View Application Events" button to the right and override OnIntialize so you can set the MinimumSplashScreenDisplayTime() like this:

进入 Project Properties 并将主窗体保留为 Startup 窗体。将您的初始屏幕表单设置为底部的初始屏幕条目。现在单击右侧的“查看应用程序事件”按钮并覆盖 OnIntialize,以便您可以像这样设置 MinimumSplashScreenDisplayTime():

Public Class Loading
  Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
    'part 1
    If Registry.LocalMachine.OpenSubKey("Hardware\Description\System\CentralProcessor
Namespace My

    ' The following events are available for MyApplication:
    ' 
    ' Startup: Raised when the application starts, before the startup form is created.
    ' Shutdown: Raised after all application forms are closed.  This event is not raised if the application terminates abnormally.
    ' UnhandledException: Raised if the application encounters an unhandled exception.
    ' StartupNextInstance: Raised when launching a single-instance application and the application is already active. 
    ' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected.
    Partial Friend Class MyApplication

        Private Sub MyApplication_Startup(sender As Object, e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) Handles Me.Startup
            If someCondition Then
                MessageBox.Show("oops")
                e.Cancel = True ' <-- main form will NOT show, app will simply exit
            End If
        End Sub

    End Class


End Namespace
").GetValue("Identifier").ToString.Contains("x86") Then My.Settings.Is64 = False Else My.Settings.Is64 = True End If 'part 2 If My.Settings.Is64 = True Then Form64.Show() Me.Close() Else MsgBox("No version developed for 32-bit computers.") End End If End Sub End Class

See herefor more information.

请参阅此处了解更多信息。

回答by Neolisk

If you want to execute the rest of your code after 5 seconds, why not create a separate thread/task, which will wait for 5 seconds and then trigger the rest of your code to run via a callback to the main thread? This approach will not hang your UI.

如果您想在 5 秒后执行其余代码,为什么不创建一个单独的线程/任务,它会等待 5 秒,然后通过对主线程的回调触发其余代码运行?这种方法不会挂起您的 UI。

EDIT:If you want a splash screen, drop a Timer control, set the interval to 5 seconds and run the rest of your code inside a Tick event handler.

编辑:如果您想要启动画面,请放下 Timer 控件,将间隔设置为 5 秒,然后在 Tick 事件处理程序中运行其余代码。

Assuming you have already set up the Timer, move your loading code into Timer1_Tickhandler:

假设您已经设置了 Timer,将加载代码移动到Timer1_Tick处理程序中:

    For i As Integer = 1 To 500
        System.Threading.Thread.Sleep(10)
        System.Windows.Forms.Application.DoEvents()
    Next

Or leave part 1 in Load, and move part 2 into Tick. I would prefer this option for semantics.

或将第 1 部分留在 中Load,将第 2 部分移入Tick。我更喜欢这个语义选项。

Also don't forget to set Timer.Enabled = True.

另外不要忘记设置Timer.Enabled = True.

回答by Idle_Mind

If you want a place to CANCEL the application, you use the Application.Startupevent and set e.Cancel = Truefrom within there. When this is done the main form will not even appear; the application will simply exit. That could look something like:

如果您想要一个取消应用程序的地方,您可以使用Application.Startup事件并e.Cancel = True从那里进行设置。完成此操作后,主窗体甚至不会出现;应用程序将简单地退出。这可能看起来像:

Private ReadOnly _resetEvent As AutoResetEvent = New AutoResetEvent(False)

Sub Pause(ByVal milliseconds As Long)
    Dim waitInterval As TimeSpan = TimeSpan.FromMilliseconds(milliseconds)
    While Not _resetEvent.WaitOne(waitInterval)
         ' Waiting!
    End While
End Sub

回答by D_Bester

just do this:

只需这样做:

Sub Pause(ByVal milliseconds As Long)
    If milliseconds <= 0 Then Return
    Dim sw As New Stopwatch()
    sw.Start()
    Dim i As Long = 0
    Do
        If i Mod 50000 = 0 Then ' Check the timer every 50,000th iteration
            sw.Stop()
            If sw.ElapsedMilliseconds >= milliseconds Then
                Exit Do
            Else
                sw.Start()
            End If
        End If
        i += 1
    Loop
End Sub

Edit: Be careful with DoEvents; it can cause problems if the user clicks on something or an event is processed when it shouldn't. See http://www.codinghorror.com/blog/2004/12/is-doevents-evil.html

编辑:小心 DoEvents;如果用户单击某物或在不应该处理的情况下处理事件,则可能会导致问题。见 http://www.codinghorror.com/blog/2004/12/is-doevents-evil.html

回答by C???

Since sleeping and busy waiting are generally frowned upon, you could do something with an AutoResetEvent:

由于睡眠和忙碌的等待通常不受欢迎,您可以使用以下命令做一些事情AutoResetEvent

Pause(5000) ' Pause for 5 seconds

This is not recommended, but here's an example using the System.Diagnostics.Stopwatchclass:

不推荐这样做,但这里有一个使用System.Diagnostics.Stopwatch类的示例:

##代码##

And then where you need to pause, just call this Pause()method:

然后你需要暂停的地方,只需调用这个Pause()方法:

##代码##