Visual Basic/How to allow control to form while running the VB Code
Expert: Golfnut_1969 - 4/13/2007
QuestionQUESTION: Hi,
I am new to VB Programming. I have written one application in VB that searches in the EXCEL and generates the results.My problem is that when the code is running i am not able to click on any other buttons provided on the form not even the minimize button also. I need to mininize the form when the search is in progress and also i have provided some buttons to stop the search in the middle. how can i gain access to these buttons when the form is running?
ANSWER: When your application is running a process any control events (Button Clicks, etc..) are not raised, rather they are queued and wait until the process is completed. However, there is a method called DoEvents that you can call that will tell your application to pause in the process and check for any queued events and raise them if they exist. You would use it like this.
Create a new project with a single form and add 2 command buttons named Command1 and Command2. Add the following code.
'This is a Windows API that tells the application to pause for a number of milliseconds. We will use it to slow down our loop.
Option Explicit
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Private mnCount As Integer
Private Sub Form_Load()
Command1.Caption = "Start"
Command2.Caption = "Stop"
Command2.Enabled = False
End Sub
Private Sub Command1_Click()
mnCount = 60
Command1.Enabled = False
Command2.Enabled = True
Do While mnCount > 0
mnCount = mnCount - 1
Command1.Caption = mnCount
Me.Refresh
Sleep 1000
DoEvents 'This checks for queued events
Loop
End Sub
Private Sub Command2_Click()
Command1.Caption = "Start"
Command1.Enabled = True
Command2.Enabled = False
mnCount = 0 'This will stop our loop
End Sub
---------- FOLLOW-UP ----------
QUESTION: Thanks for the response.. I have implemented the code but i have one more problem.When the search is in the middle if i click on stop it should ask me for Yes or No and based on the option that i select the program should continue.. i.e when i say no then the program should resume the execution from the place where i had stopped. how can i acheive this...
Please help me
AnswerFor the sample I gave in the previous answer, change the code in the Command2 click event as follows.
Private Sub Command2_Click()
Dim enmMsgBxRslt As VbMsgBoxResult
Dim sMsg As String
sMsg = "Do you want to stop processing?"
enmMsgBxRslt = MsgBox(sMsg, vbYesNo + vbQuestion, "Stop Execution")
If enmMsgBxRslt = vbYes Then
'Only stop processing if the user clicked the Yes Button
Command1.Caption = "Start"
Command1.Enabled = True
Command2.Enabled = False
mnCount = 0 'This will stop our loop
End If
End Sub