Hi everyone,

I have experienced a problem of events in the big VB6 project of my company that I did not resolve. To help you understand the problem, I have created a small projet which highlights the problem.

My small projet is made up of two forms. There are three controls on the main form (Name : frmForm1) : a MSHFlexGrid control (Name : grdGrid), a command button control (Name : cmdButton) and a textbox control (Name : txtField). I have set the TabStop property to False for cmdButton.

The second form (Name : frmForm2) is empty with a yellow background color. The second form is shown from the main form as a modal form.

Here is the code contained in the main form :
Code:
Option Explicit

Private mblnFirstTime   As Boolean '< False when the grid get the focus after the first time.

Private Sub Form_Load()
    ' Define the initial active cell.
    grdGrid.Col = 0
    grdGrid.Row = 1
    
    ' Initialise the form-level boolean.
    mblnFirstTime = True
End Sub

Private Sub grdGrid_GotFocus()
    ' Check if the grid get the focus for the first time.
    If Not (mblnFirstTime) Then
        txtField.Visible = False
        grdGrid_KeyPress vbKeyTab
    Else
        mblnFirstTime = False
    End If
End Sub

Private Sub grdGrid_KeyPress(KeyAscii As Integer)
    If (KeyAscii = vbKeyTab) Then
        ' Move the active cell into the right column.
        grdGrid.Col = grdGrid.Col + 1
        
        ' Show the field and set the focus to it.
        txtField.Visible = True
        txtField.SetFocus
    End If
End Sub

Private Sub cmdButton_Click()
    ' Display a modal form.
    frmForm2.Show vbModal
    
    ' Set the focus to the field.
    txtField.SetFocus
End Sub
What I expect :
I launch the program. The grdGrid get the focus. The boolean mblnFirstTime is set to False. Then I click on cmdButton. The form frmForm2 is displayed, I close it then txtField get the focus.

What I experience :
The process describe above does not happen. After clicking on cmdButton, frmForm2 is displayed as expected. But, when I close frmForm2 then an error is raised. The error window tells me that grdGrid.Col has got its maximum value. It means that grdGrid_KeyPress is called as many times as possible. grdGrid_GotFocus is consequently called as many times as possible too. I am finally wondering : Why does the grid got the focus as many times as possible ?

The following images show my experienced problem :

http://img857.imageshack.us/i/mshfgstangeevent1.png/

http://img703.imageshack.us/i/mshfgstangeevent2.png/

http://img20.imageshack.us/i/mshfgstangeevent3.png/

I suspect the problem coming from the execution order of events but I did not find any interesting information about it on the Internet.

I would really appreciate any help.