如果你能把这段程序运行起来,你就明白了
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Menus, StdCtrls, Buttons, ExtCtrls, ComCtrls;
type
TForm1 = class(TForm)
Label1: TLabel;
ComboBox1: TComboBox;
Button1: TButton;
PopupMenu1: TPopupMenu;
ScrollBox1: TScrollBox;
Button2: TButton;
procedure FormCreate(Sender: TObject);
procedure PopupMenuClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure ContextPopup(Sender: TObject;
MousePos: TPoint;
var Handled: Boolean);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
PopupControl: TControl;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
RegisterClasses([TButton,TEdit,TMemo,TComboBox,TSpeedButton,
TShape,TListBox,TLabel,TCheckBox,TRadioButton,TGroupBox,
TRadioGroup,TPanel,TBitBtn,TStaticText,TRichEdit,TUpDown,
TTrackBar,TProgressBar,TTabControl,TPageControl]);
Caption := '使用右键弹出菜单删除控件';
Font.Name := '宋体';
Font.Charset := GB2312_CHARSET;
Font.Size := 9;
Label1.Caption := '请输入类名:';
ComboBox1.Items.CommaText := 'TButton,TEdit,TMemo,TComboBox' +
',TSpeedButton,TShape,TListBox';
ComboBox1.ItemIndex := 0;
Button1.Caption := '创建控件';
Button2.Caption := '全部删除';
PopupMenu1.Items.Add(NewItem(
'删除控件', 0, False, True, PopupMenuClick, 0,
'DeleteControlItem'
));
Button1.OnClick := Button1Click;
Button2.OnClick := Button2Click;
end;
procedure TForm1.PopupMenuClick(Sender: TObject);
begin
//删除弹出菜单的控件
try
if Assigned(PopupControl) and (PopupControl is TControl) then
begin
FreeAndNil(PopupControl);
end;
except
ShowMessage('对象可能已经删除');
end;
end;
type
TControlCrack = class(TControl);
procedure TForm1.Button1Click(Sender: TObject);
var
tmp: TControl;
ctrlclass: TControlClass;
tmpclass: TPersistentClass;
begin
tmpclass := GetClass(ComboBox1.Text);
if Assigned(tmpclass) then
begin
if tmpclass.InheritsFrom(TControl) then
begin
ctrlclass := TControlClass(tmpclass);
tmp := ctrlclass.Create(Self);
tmp.Left := Random(300);
tmp.Top := Random(200);
tmp.Parent := ScrollBox1;
TControlCrack(tmp).PopupMenu := PopupMenu1;
TControlCrack(tmp).OnContextPopup := ContextPopup;
end
else
ShowMessage('您输入的不是控件类,无法创建');
end
else
ShowMessage('不可识别的类名,或类未注册');
end;
procedure TForm1.ContextPopup(Sender: TObject;
MousePos: TPoint;
var Handled: Boolean);
begin
PopupControl := TControl(Sender);
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
while ScrollBox1.ControlCount > 0do
ScrollBox1.Controls[0].Free;
end;
end.