delphidelphi-xe2

Delphi Error: "Cannot focus a disabled or invisible window"


I'm getting an error when running my compiled program. I've taken every precaution I can think of to prevent the error such as enabling forms before I hide or focus them. The application shows a DimmerForm (grey fade overlay) and then a NewFileForm on top of the overlay. The NewFileForm does its stuff and determines the file that is to be made and creates a new tabsheet in the page control on the MainForm and shows the newly created tab sheet. All this works so far (I can break before the NewFileForm closes and any error occurs and see that the tab sheet has been created and shown successfully). The NewFileForm then closes, which is again working fine.

The error happens when anything then tries to set the focus back to the MainForm. Hiding the DimmerForm, or clicking on the MainForm, or setting focus to the MainForm through code all cause the error message to occur. Placing the code in a {try, except, end} doesn't prevent the error message either. I've searched every other method in the code that could possibly be triggered by the focusing of the MainForm and none are entered before the error occurs (so can't be causing it).

I wrote pretty much the exact same code in a previous version of my application and then decided to restructure it all from the ground up. The previous version of the application worked without a hitch with the form focusing.

Here is the code to open up the NewFileForm:

procedure TMainForm.NewFilesToolButtonClick(Sender: TObject);
begin

  ShowDimmer;
  NewFileForm.ShowModal;
  HideDimmer;

end;

Here is the code to show the dimmer form:

procedure ShowDimmer;
begin

  // Enable to prevent errors
  DimmerForm.Enabled := true;

  // Hide dimmer form and show mainform
  DimmerForm.Show;

end;

Here is the code to hide the dimmer form:

procedure HideDimmer;
begin

  // Enable to prevent errors
  DimmerForm.Enabled := true;
  MainForm.Enabled := true;

  // Hide dimmer form and show mainform
  DimmerForm.Hide;
  MainForm.SetFocus;

end;

Solution

  • Generally you are calling focus to something that is not yet created (on the form you are in the process of creating), try moving some of the onCreate code to onShow. Without more detail it is hard to tell what is happening but try this.