Search code examples
delphitformtlistbox

How to display a control (e.g. TListbox) beyond the borders of a TForm


How can I display a Listbox beyond the borders of the parent Form at runtime:

enter image description here

The image is obtained from the IDE when clicking on the listbox in design time. I would like to achieve this effect at runtime.


Solution

  • You can not really visually extend the control outside of the parent form. But you can achieve the effect by creating a separate borderless form for this control and display this secondary form partly over the first form:

    enter image description here

    Here Form1 is a main form, with following OnClick handler for Button1:

    procedure TForm1.Button1Click(Sender: TObject);
    begin
      Form2 := TForm2.Create(nil);
      try
        Form2.Left := ClientOrigin.X + 140;
        Form2.Top := ClientOrigin.Y + ClientHeight - 20;
        Form2.ShowModal;
        Edit1.Text := IntToStr(Form2.ModalResult);
      finally
        Form2.Free;
      end;
    end;
    

    Since the second form (Form2) is not related (child - parent wise) to Form1 we must give its location as screen pixels, but still relative to Form1. Therefore we use the Form1.ClientOrigin (`Form1 client area top and left as screen coordinates) as reference.

    The second form, Form2 that holds the TListBox, has following property settings

    BorderStyle = bsNone
    KeyPreview = True (to catch `Enter` key)
    

    and it has the OnKeyUp event handler written as

    procedure TForm2.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
    begin
      if Key = VK_RETURN then
        ModalResult := ListBox1.ItemIndex;
    end;