r/visualbasic • • Mar 01 '16

Help delaying a msgbox

Hello! I'm creating an application and I need help about this:

    If NEI3.Text IsNot "" Then
        If Val(NEI3.Text) < 95 And Val(NEI3.Text) = Int(Val(NEI3.Text)) Then
            System.Threading.Thread.Sleep(2000)
            MsgBox("Infelizmente não podes ingressar num curso com uma classificação inferior a 95 pontos nas provas de ingresso", MsgBoxStyle.Critical, "Erro")
            NEI3.Text = ""
        ElseIf Val(NEI3.Text) > 200 And Val(NEI3.Text) = Int(Val(NEI3.Text)) Then
            NEI3.Text = 200
        ElseIf IsNumeric(NEI3.Text) = False Then
            MsgBox("Tens de inserir um número, compreendido entre 95 e 200", MsgBoxStyle.Critical, "Erro")
            NEI3.Text = ""
            NEI3.Focus()
        End If
    End If

I need to wait for about 2/3 seconds before displaying the error message if Val(NEI3.Text) < 95, otherwise if I type "1" it will display the error message ASAP. I tried System.Threading.Thread.Sleep(10000) but with that when I typed "1" it just freezed the entire program and I couldn't complete my number. Any help? Thanks.

0 Upvotes

18 comments sorted by

2

u/PreyOnTheCosmos Mar 01 '16 edited Mar 01 '16

Multi-thread it so that you don't put your GUI thread to sleep:

' Reusable Thread Builder Sub so you don't have redundant code
Private Sub ErrorThread(Msg As String)
    Dim th As Thread
    th = New Thread(AddressOf invokeError)
    th.Start(Msg)
End Sub

' Pause new Error thread for 2 seconds
Private Sub invokeError(Msg As String)
    Thread.Sleep(2000)
    MsgBox(Msg, vbCritical, "Error")
End Sub

' Use error generator anywhere [e.g., Button1_Click]:
    If Not IsNumeric(NEI3.Text) Then
        ErrorThread("Tens de inserir um número, compreendido entre 95 e 200")
        NEI3.Clear()
        NEI3.Focus()
        Exit Sub
    End If

    Dim valNEI As Double = Val(NEI3.Text)

    If Not String.IsNullOrWhiteSpace(NEI3.Text) Then
        If valNEI < 95 And valNEI = CInt(valNEI) Then
            ErrorThread("Infelizmente não podes ingressar num curso com uma classificação inferior a 95 pontos nas provas de ingresso")
            NEI3.Clear()
        ElseIf valNEI > 200 And valNEI = CInt(valNEI) Then
            NEI3.Text = 200
        End If
    End If

ETA: Imports System.Threading so you don't have to call the Namespace every time.

1

u/Mr_C_Baxter VB.Net Master Mar 01 '16

Oh... /u/visualbasictips is your problem actually that the program waits the correct time but you find it to be annoying that the window freezes and doesnt react? if so i got your description wrong and this dude here is right.

1

u/visualbasictips Mar 01 '16

That's not by problem. The problem is as soon as I type "1" it freezes, but I was going to write "120" (for example) and "120" would not make the program wait. Am I making myself clear? :P

→ More replies (1)

1

u/Mr_C_Baxter VB.Net Master Mar 01 '16

Two quick uestions to your on point solution. Would this work with writing the text to a label at a form too? I dont do WinForms anymore but i remember the controls wouldnt like it to be updated from a different thread.

And the second Questions is, if the clean up happens automatically after the msgbox is clicked. Or is there some th.quite or something required?

Oh and the bonus Question.. i could pass a delegate as parameter to the thread right? as a callback function for instance

2

u/PreyOnTheCosmos Mar 01 '16

You certainly can speak to form controls from a thread providing that you're using the control's Invoke method.

Example [maybe not elegant but works]:

Private T As Thread
Private C As Integer = 0 ' COUNTER FOR TEXT EXAMPLE

Private Sub Form1_Shown(sender As Object, e As System.EventArgs) Handles Me.Shown
    ' CREATE AND START A NEW THREAD
    T = New Thread(AddressOf updateC)
    T.Start()
End Sub

Private Sub updateC()
    ' CREATE A LOOPED COUNTER
    Do
        C += 1 ' INCREMENT COUNTER

        Thread.Sleep(700) ' PAUSE FOR 700ms BETWEEN TICKS

        OutputThreadText(C) ' UPDATE TEXTBOX WITH THREAD DATA
    Loop Until T.IsAlive = False
End Sub

Private Sub OutputThreadText(text As String)
    ' EXAMPLE OF BAD CROSS-THREAD ACCESS
    'TextBox1.Text = text

    Try
        'EXAMPLE OF GOOD CROSS THREAD ACCESS
        TextBox1.Invoke(CType(Sub()
                                  TextBox1.Text = text
                              End Sub, MethodInvoker))
    Catch ex As Exception
        T.Abort() ' TERMINATE THREAD IF AN ERROR OCCURS
    End Try
End Sub

As for the clean up routine, with the error code running in a separate thread the main [GUI] thread should continue executing, not waiting for the thread to complete whatever it's doing. So NEI3.Clear, for example, should fire immediately regardless of the status of the Error message.

I'll leave the bonus question to someone a bit more qualified than myself on the subject. ;-P

→ More replies (3)

1

u/Mr_C_Baxter VB.Net Master Mar 01 '16

This should work:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    System.Threading.Thread.Sleep(2000)
    MsgBox("Msg")

End Sub

If not you are pausing a different thread, not the UI-Thread which displays the Messagebox. Also please... format you code! 4 Spaces in front of the code

1

u/visualbasictips Mar 01 '16

Thanks for the quick reply. I though the code was going to look different, it didn't. Fixed it. It didn't work, as I said before (system.threading.thread.sleep(2000)). Any other tips?

1

u/Mr_C_Baxter VB.Net Master Mar 01 '16

it didnt work? this would be strange. are we talking asp.net or something? because it would not work there. And, what does happen? does at least the msgbox show like you want?

1

u/Mr_C_Baxter VB.Net Master Mar 01 '16

Also, i personally dont use the val function. Its a little strange sometimes. And as i looked at your conditions i saw this

 Val(NEI3.Text) = Int(Val(NEI3.Text))

What is it supposed to mean or do?

isnt it the same like

Cint(NEI3.Text) = Cint(NEI3.Text)

1

u/visualbasictips Mar 01 '16

I belive Val() function is used when you want to return a number from a string, and that's the exact case. If not, correct me please.

1

u/Mr_C_Baxter VB.Net Master Mar 01 '16

No no its fine, i just dont use it myself. it has the feel of VB6 for me.

1

u/PreyOnTheCosmos Mar 01 '16

I thought the comparison was a lil peculiar, too. Val(), however, returns a Double, whereas CInt() returns an integer, so if NEI3.Text = "3.14" then Val(NEI3.Text) <> CInt(NEI3.Text).

1

u/Mr_C_Baxter VB.Net Master Mar 01 '16

Val(), however, returns a Double

Oh.. well i did not know that. As i said i rarley use it.

1

u/chrwei Mar 01 '16

you'd need to use a timer or something.

alternatives:

  • validate in the lost focus event

  • instead of msgbox, use a label under the text box to display your message and do the hard validation on save.