I'm trying to make a button that when pressed for a short while will close the form but when pressed for a long time e.g. 5s the form's process will be killed.

I'm trying to achieve this with a timer.

    Private Sub CloseLongTimer_Tick(sender As Object, e As EventArgs) Handles CloseLongTimer.Tick

        Dim SetTime As Integer = 0
        SetTime = SetTime + 1

        If SetTime < 500 Then

            Me.Close()

        ElseIf SetTime > 499 And SetTime < 1001 Then

            System.Environment.Exit(1)

        ElseIf SetTime > 1000 Then

            CloseLongTimer.Stop()

        End If

    End Sub

    Private Sub CloseButton_MouseDown(sender As Object, e As EventArgs) Handles CloseButton.MouseDown

        CloseLongTimer.Start()

    End Sub

Any help? I think it's a problem in logic. Thanks.

You could perhaps test the time between a MouseDown and MouseUp event of the button.

Public Class Form1
    Dim Seconds As String
    Private Sub Button1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles CloseButton.MouseDown
        Seconds = 0
        CloseLongTimer.Interval = 1000
        CloseLongTimer.Start()
    End Sub
    Private Sub CloseLongTimer_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles CloseLongTimer.Tick
        Seconds += 1
    End Sub
    Private Sub CloseButton_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles CloseButton.MouseUp
        CloseLongTimer.Stop()
        If Seconds < 5 Then
            Me.Close()
        Else
            System.Environment.Exit(1)
        End If
    End Sub
End Class
    //my shortest solution for this problem:

    private bool mouseUp = false;
    private const int holdButtonDuration = 2000; //milliseconds
    private void btnTest_MouseDown(object sender, MouseEventArgs e)
    {
        mouseUp = false;
        Stopwatch sw = new Stopwatch();
        sw.Start();
        while (e.Button == MouseButtons.Left && e.Clicks == 1 && (mouseUp == false && sw.ElapsedMilliseconds < holdButtonDuration))
            Application.DoEvents();
        if (sw.ElapsedMilliseconds < holdButtonDuration)
            btnTest_ShortClick(sender, e);
        else
            btnTest_LongClick(sender, e);
    }
    private void btnTest_MouseUp(object sender, MouseEventArgs e)
    {
        mouseUp = true;
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.