Search code examples
delphifocusdelphi-7dbgrid

DBGrid focus bug on MDI


I got a DbGrid focus bug when I have it inside a MDIChildForm.

To reprocedure the bug:

  • Create a MDI application
  • At the main form, put a Panel and a Edit inside it
  • Create a MDI Child form
  • Put a DBGrid and assign data (with more than 1 record)

dbgrid focus bug on mdi

Now, run the application, and follow the steps:

  • Click on the Grid, to focus at the first row
  • Click on the Edit, to focus it
  • Now try to click at another row of the dbgrid.

Bug:

  • The dbgrid doesn't receives the focus, nothing happends!

I'm using Delphi 7.

Can someone help me with an workaround?


Solution

  • The problem is created by the Form.ActiveControl.

    In this case, the MDI child is retaining the DBGrid as the active control after the Edit focused, and because of this the Windows.SetFocus isn't called after the dbgrid is clicked.

    I solve the problem by overriding the TDBGrid.SetFocus:

    type
        TMyDBGrid = class(TDBGrid)
        public
           procedure SetFocus; override;
        end;
    
    procedure TMyDBGrid.SetFocus;
    var
      form: TCustomForm;
    begin
      inherited;
    
      // BUG-FIX: force the SetFocus if the current Control is Self but not focused!
      form := GetParentForm(Self);
      if (form <> nil) and (form.ActiveControl = Self) and not Focused then
        Windows.SetFocus(Self.Handle);
    end;