none
How do I close a form which is in a constant loop ? RRS feed

  • Question

  •  I can close the form as long as it is not in the loop, but once I place it in the loop I cannot stop it.

    Public Class Form1
        Public Declare Sub mouse_event Lib "user32" Alias "mouse_event" (ByVal dwflags As Long)
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim InfiniteLoop As Boolean = True
    
            For i = 1 To 45687894
                If i = 45687893 And InfiniteLoop = True Then i = 1
                Cursor.Position = New Point(200, 200)
                Cursor.Position = New Point(400, 400)
            Next
    
        End Sub
    
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            AddHandler Me.KeyDown, AddressOf CheckKeyDown
            For Each C As Control In Me.Controls
                AddHandler C.KeyDown, AddressOf CheckKeyDown
            Next
        End Sub
        Sub CheckKeyDown(ByVal sender As Object, ByVal e As KeyEventArgs)
            If e.KeyCode = Keys.Escape Then
                Me.Close()
            End If
        End Sub
    End Class



    • Edited by VBShaper Wednesday, November 14, 2018 4:46 PM
    Wednesday, November 14, 2018 4:32 PM

Answers

  • You have two threads going that are basically the same.  Get rid of button 1 and add this instead.

        Private MoveMouseTask As task
        Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
            MoveMouseTask = Task.Run(Sub()
                                         _MoveMouse()
                                     End Sub)
        End Sub
    
        Private Sub _MoveMouse()
            Dim toggle As Boolean = False
            Do
                Threading.Thread.Sleep(60 * 1000) 'one minute
                'code to move mouse here <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
                toggle = Not toggle
                If toggle Then
                Else
                End If
            Loop
        End Sub

    You'll need to add the code to move the mouse.  If you do this and the Form has a close box you won't need to check for the Escape key, you can just close the Form normally.


    "Those who use Application.DoEvents() have no idea what it does and those who know what it does never use it."

    - from former MSDN User JohnWein

    SerialPort Info

    Multics - An OS ahead of its time.



    • Edited by dbasnett Wednesday, November 14, 2018 6:56 PM
    • Marked as answer by VBShaper Thursday, November 15, 2018 11:38 AM
    Wednesday, November 14, 2018 5:44 PM

All replies

  • Hi

    Well, you did use a code block in this post - well done!

    It is not surprising that you can't exit your application. First you mess with the mouse, and, you build a stupid infinit loop.

    *

    If you explain clearly what you are trying to achieve, we may be able to offer something better.


    Regards Les, Livingston, Scotland

    Wednesday, November 14, 2018 5:08 PM
  • Hi

    Here is a VBShaper emulator code. You can stop this version but you have to be quick.

    ' Form1 with Button1 and
    ' Timer1
    Option Strict On
    Option Explicit On
    Public Class Form1
      Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        With Timer1
          ' do not use less than 1000ms
          ' otherwise you would be back
          ' to your original infinite 
          ' loop effect.
          .Interval = 1000
          .Enabled = Not .Enabled
        End With
      End Sub
      Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        Static b As Boolean = True
        b = Not b
        Select Case b
          Case True
            Cursor.Position = New Point(200, 200)
          Case Else
            Cursor.Position = New Point(400, 400)
        End Select
      End Sub
    End Class


    Regards Les, Livingston, Scotland


    • Edited by leshay Wednesday, November 14, 2018 5:20 PM
    Wednesday, November 14, 2018 5:19 PM
  • Hi

    Well, you did use a code block in this post - well done!

    It is not surprising that you can't exit your application. First you mess with the mouse, and, you build a stupid infinit loop.

    *

    If you explain clearly what you are trying to achieve, we may be able to offer something better.


    Regards Les, Livingston, Scotland

    I was using this to simulate mouse movement, so the PC would not go into sleep mode.

    Wednesday, November 14, 2018 5:34 PM
  • You have two threads going that are basically the same.  Get rid of button 1 and add this instead.

        Private MoveMouseTask As task
        Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
            MoveMouseTask = Task.Run(Sub()
                                         _MoveMouse()
                                     End Sub)
        End Sub
    
        Private Sub _MoveMouse()
            Dim toggle As Boolean = False
            Do
                Threading.Thread.Sleep(60 * 1000) 'one minute
                'code to move mouse here <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
                toggle = Not toggle
                If toggle Then
                Else
                End If
            Loop
        End Sub

    You'll need to add the code to move the mouse.  If you do this and the Form has a close box you won't need to check for the Escape key, you can just close the Form normally.


    "Those who use Application.DoEvents() have no idea what it does and those who know what it does never use it."

    - from former MSDN User JohnWein

    SerialPort Info

    Multics - An OS ahead of its time.



    • Edited by dbasnett Wednesday, November 14, 2018 6:56 PM
    • Marked as answer by VBShaper Thursday, November 15, 2018 11:38 AM
    Wednesday, November 14, 2018 5:44 PM
  • In regards to simulating mouse movement to avoid sleep mode, I wrote a tray app that might be what you are looking for BUT I did this in C# so you can a) compile/use b) examine the source and get ideas from it.

    https://1drv.ms/f/s!AtGAgKKpqdWjiigGOMGF2jvKKZqd


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Wednesday, November 14, 2018 5:53 PM
    Moderator
  • Hello,

    You can use background worker for your infinite loop, hope below code helps you

    Add Background worker on form 

    Imports System.ComponentModel
    
    Public Class Form20
        Public Declare Sub mouse_event Lib "user32" Alias "mouse_event" (ByVal dwflags As Long)
        Private Sub Form20_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
            AddHandler Me.KeyDown, AddressOf CheckKeyDown
            For Each C As Control In Me.Controls
                AddHandler C.KeyDown, AddressOf CheckKeyDown
            Next
        End Sub
        Sub CheckKeyDown(ByVal sender As Object, ByVal e As KeyEventArgs)
            If e.KeyCode = Keys.Escape Then
                Me.Close()
            End If
        End Sub
        Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
            BackgroundWorker1.RunWorkerAsync()
        End Sub
        Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
            Dim InfiniteLoop As Boolean = True
            For i = 1 To 45687894
                If i = 45687893 And InfiniteLoop = True Then i = 1
                Cursor.Position = New Point(200, 200)
                Cursor.Position = New Point(400, 400)
            Next
        End Sub
    End Class

    Wednesday, November 14, 2018 6:15 PM
  • Hello,

    You can use background worker for your infinite loop, hope below code helps you

    Add Background worker on form 

    Imports System.ComponentModel
    
    Public Class Form20
        Public Declare Sub mouse_event Lib "user32" Alias "mouse_event" (ByVal dwflags As Long)
        Private Sub Form20_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
            AddHandler Me.KeyDown, AddressOf CheckKeyDown
            For Each C As Control In Me.Controls
                AddHandler C.KeyDown, AddressOf CheckKeyDown
            Next
        End Sub
        Sub CheckKeyDown(ByVal sender As Object, ByVal e As KeyEventArgs)
            If e.KeyCode = Keys.Escape Then
                Me.Close()
            End If
        End Sub
        Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
            BackgroundWorker1.RunWorkerAsync()
        End Sub
        Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
            Dim InfiniteLoop As Boolean = True
            For i = 1 To 45687894
                If i = 45687893 And InfiniteLoop = True Then i = 1
                Cursor.Position = New Point(200, 200)
                Cursor.Position = New Point(400, 400)
            Next
        End Sub
    End Class

    NO - do not use this as is!!!!!!!

    Did you try this before posting????????


    "Those who use Application.DoEvents() have no idea what it does and those who know what it does never use it."

    - from former MSDN User JohnWein

    SerialPort Info

    Multics - An OS ahead of its time.

    Wednesday, November 14, 2018 6:28 PM
  • Yes I am able to close the form when Escape key pressed.
    Wednesday, November 14, 2018 6:37 PM
  • Yes I am able to close the form when Escape key pressed.

    That wasn't the point.  What did your cursor do?  Did it move once per minute?

    "Those who use Application.DoEvents() have no idea what it does and those who know what it does never use it."

    - from former MSDN User JohnWein

    SerialPort Info

    Multics - An OS ahead of its time.

    Wednesday, November 14, 2018 6:54 PM
  • Question was about closing form when infinite loop is going on not about triggering mouse move at every one minute

    I have answered about triggering mouse move at every one minute here

    https://social.msdn.microsoft.com/Forums/en-US/a45efed8-b705-4f70-a679-40ea43619c26/how-do-i-use-a-timer-from-a-button-press?forum=vbgeneral

    Wednesday, November 14, 2018 7:15 PM
  • Question was about closing form when infinite loop is going on not about triggering mouse move at every one minute

    I have answered about triggering mouse move at every one minute here

    https://social.msdn.microsoft.com/Forums/en-US/a45efed8-b705-4f70-a679-40ea43619c26/how-do-i-use-a-timer-from-a-button-press?forum=vbgeneral

    The OP shouldn't have had two threads about this, but you knew.  Also, the code you posted is a big ol' busy loop.

    Do what you want, it just isn't for me.


    "Those who use Application.DoEvents() have no idea what it does and those who know what it does never use it."

    - from former MSDN User JohnWein

    SerialPort Info

    Multics - An OS ahead of its time.

    Wednesday, November 14, 2018 7:20 PM
  • What you want me to do sir......I saw two threads with two different questions so posted different solutions. If my solution is having problem please let me know i will rectify it
    Wednesday, November 14, 2018 7:23 PM
  • What you want me to do sir......I saw two threads with two different questions so posted different solutions. If my solution is having problem please let me know i will rectify it

    Open task manager.  Go to the performance tab.  Run your code.  That is why I have an issue with it.  But as I said do what you want.

    @OP - there is some good info here in the accepted answer FWIW

    https://stackoverflow.com/questions/2479403/stop-the-screen-saver-and-hibernation-temporarily-in-vb-net


    "Those who use Application.DoEvents() have no idea what it does and those who know what it does never use it."

    - from former MSDN User JohnWein

    SerialPort Info

    Multics - An OS ahead of its time.


    • Edited by dbasnett Wednesday, November 14, 2018 7:30 PM
    Wednesday, November 14, 2018 7:29 PM
  • Thanks for the info sir I will check.
    Wednesday, November 14, 2018 7:36 PM
  • What you want me to do sir......I saw two threads with two different questions so posted different solutions. If my solution is having problem please let me know i will rectify it

    Open task manager.  Go to the performance tab.  Run your code.  That is why I have an issue with it.  But as I said do what you want.

    @OP - there is some good info here in the accepted answer FWIW

    https://stackoverflow.com/questions/2479403/stop-the-screen-saver-and-hibernation-temporarily-in-vb-net


    "Those who use Application.DoEvents() have no idea what it does and those who know what it does never use it."

    - from former MSDN User JohnWein

    SerialPort Info

    Multics - An OS ahead of its time.


    Here is a class that allows an app to tell the system not to go to sleep or shutdown the display.  I did NOT test it rigorously but it did seem to work

    ''' <summary>
    ''' Simple power manager class that enables applications to inform the system
    ''' that it is in use, thereby preventing the system from entering the sleeping
    ''' power state or turning off the display while the application is running.
    ''' </summary>
    Public Class PowerManager
    
        ''' <summary>
        ''' Enables applications to inform the system that it is in use, thereby preventing the system from entering the sleeping power state or turning off the display while the application is running.
        ''' </summary>
        ''' <param name="esFlags">The thread's execution requirements. This parameter can be one or more of the EXECUTION_STATE values.</param>
        ''' <returns>
        ''' <para>If the function succeeds, the return value is the PREVIOUS thread execution state, as a EXECUTION_STATE value.</para>
        ''' <para>If the function fails, the return value is NULL.</para>
        '''</returns>
        ''' <remarks>
        ''' </remarks>
        Private Declare Function SetThreadExecutionState Lib "kernel32" (ByVal esFlags As EXECUTION_STATE) As EXECUTION_STATE
    
        <Flags> Public Enum EXECUTION_STATE As Integer
    
            ''' <summary>
            ''' Informs the system that the state being set should remain in effect until the next call that uses ES_CONTINUOUS and one of the other state flags is cleared.
            ''' </summary>
            ES_CONTINUOUS = &H80000000
    
            ''' <summary>
            ''' Forces the display to be on by resetting the display idle timer.
            ''' </summary>
            ES_DISPLAY_REQUIRED = &H2
    
            ''' <summary>
            ''' Forces the system to be in the working state by resetting the system idle timer.
            ''' </summary>
            ES_SYSTEM_REQUIRED = &H1
    
        End Enum
    
        ''' <summary>
        ''' do not enter sleeping power state or turn off the display 
        ''' </summary>
        ''' <returns>PREVIOUS thread execution state</returns>
        ''' <remarks></remarks>
        Public Shared Function StopPowerSave() As EXECUTION_STATE
            Return SetThreadExecutionState(EXECUTION_STATE.ES_SYSTEM_REQUIRED Or EXECUTION_STATE.ES_DISPLAY_REQUIRED Or EXECUTION_STATE.ES_CONTINUOUS)
        End Function
    
        ''' <summary>
        ''' Normal system settings
        ''' </summary>
        ''' <returns>PREVIOUS thread execution state</returns>
        ''' <remarks></remarks>
        Public Shared Function EnablePowerSave() As EXECUTION_STATE
            Return SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS)
        End Function
    
    End Class
    

    This was from the SO link I posted with some minor changes.


    "Those who use Application.DoEvents() have no idea what it does and those who know what it does never use it."

    - from former MSDN User JohnWein

    SerialPort Info

    Multics - An OS ahead of its time.

    Thursday, November 15, 2018 2:53 PM