Home  |   French  |   About  |   Search  | mvps.org  

What's New
Table Of Contents
Credits
Netiquette
10 Commandments 
Bugs
Tables
Queries
Forms
Reports
Modules
APIs
Strings
Date/Time
General
Downloads
Resources
Search
Feedback
mvps.org

In Memoriam

Terms of Use


VB Petition

API: Interrupt running code

Author(s)
Dev Ashish

(Q)    How can I interrupt code that's running within a loop through a keystroke?

(A)    You can use GetAsyncKeyState API for this.  Here's an example of a loop that adds n records within a loop and where the code can be interrupted by pressing the Escape key.

'************ Code Start ***********
' This code was originally written by Dev Ashish.
' It is not to be altered or distributed,
' except as part of an application.
' You are free to use it in any application,
' provided the copyright notice is left unchanged.
'
' Code Courtesy of
' Dev Ashish
'
Private Declare Function apiGetAsyncKeyState Lib "user32" _
        Alias "GetAsyncKeyState" _
        (ByVal vKey As Long) _
        As Integer
        
Private Const VK_ESCAPE = &H1B

Function fBreakInCode()
Dim boolEsc As Boolean
Dim db As Database
Dim rs As Recordset
Dim i As Integer

    Set db = CurrentDb
    Set rs = db.OpenRecordset("SomeTable", dbOpenDynaset)
    For i = 1 To 20000
        If apiGetAsyncKeyState(VK_ESCAPE) Then
              If MsgBox("You pressed Escape! Do you wish to stop?", _
                         vbYesNo, "Please confirm") = vbYes Then
                          Exit For
              End If
        End If
        With rs
            .AddNew
                !Field1 = i
                !Field2 = i * 2
                !Field3 = i * 3
            .Update
            i = i + 1
        End With
    Next
    rs.Close
    Set rs = Nothing
    MsgBox "Finished.  Added " & i & " records!"
End Function
'*************** Code End ************

© 1998-2010, Dev Ashish & Arvin Meyer, All rights reserved. Optimized for Microsoft Internet Explorer