InsertObject (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

For the following example, add a button, a status bar, and a list box to the form. Set the SimplePanel property of the status bar to True, using the object inspector. Also, populate the OnMouseUp event handler for the list box. The following code fills a list box with the names of all components on the form, when you click the button. References to the components themselves are inserted along with the names. The components are all inserted at the front of the list, so that the last component added to the form is the first component in the list. When you right-click the name of an object in the list, the component�s coordinates are displayed on the status bar. Note: Because you are using the right- click, the item need not be selected.

Code

procedure TForm1.Button1Click(Sender: TObject);
var
  I: Integer;
begin
  for I := 0 to Form1.ComponentCount-1 do
    ListBox1.Items.InsertObject(
      0, Form1.Components[I].Name, 
      Form1.Components[I] as TObject);
end;

procedure TForm1.ListBox1MouseUp(
  Sender: TObject; Button: TMouseButton; 
  Shift: TShiftState; X,Y: integer);
var
  APoint: TPoint;
  Index: integer;
  TheObject: TControl;
begin
  if Button = mbRight then
  begin
  APoint.X := X;
  APoint.Y := Y;
  Index := ListBox1.ItemAtPos(APoint, True);
  if (ListBox1.Items.Objects[Index] is TControl) then 
  begin
    TheObject := 
      (ListBox1.Items.Objects[Index] as TControl);
    StatusBar1.SimpleText := TheObject.Name + ' is at (' +
                           IntToStr(TheObject.Left) + ', ' +
                           IntToStr(TheObject.Top) + ') ';
  end
  else
    Beep;
  end;
end;

Uses