我正在做一个自定义组件,Delphi XE2中TComponent的后代,我想右键单击它并有2个选项:Next和Previous(例如)
怎么办?请提供代码段或示例。
该选项应该在设计时出现,右键单击表单上放置的组件,现在是TComponent的后代。但如果有更好的选择来获得功能,则不需要这样做。
下一个和上一个将用于根据集合中的主题切换组件的颜色(通过所有者组件列表)。
答案 0 :(得分:6)
您需要为组件注册自定义组件编辑器,并覆盖以下三种方法:
function GetVerbCount: Integer;
function GetVerb(Index: Integer): string;
procedure ExecuteVerb(Index: Integer);
这是一个(非常极小的)示例,在Delphi 2007中快速抛出:
MyTestComponentPackage.dpk
- 一个新的VCL包(File-> New-> Package)
package MyTestComponentPackage;
{$R *.res}
{$ALIGN 8}
{$ASSERTIONS ON}
{$BOOLEVAL OFF}
{$DEBUGINFO ON}
{$EXTENDEDSYNTAX ON}
{$IMPORTEDDATA ON}
{$IOCHECKS ON}
{$LOCALSYMBOLS ON}
{$LONGSTRINGS ON}
{$OPENSTRINGS ON}
{$OPTIMIZATION ON}
{$OVERFLOWCHECKS OFF}
{$RANGECHECKS OFF}
{$REFERENCEINFO ON}
{$SAFEDIVIDE OFF}
{$STACKFRAMES OFF}
{$TYPEDADDRESS OFF}
{$VARSTRINGCHECKS ON}
{$WRITEABLECONST OFF}
{$MINENUMSIZE 1}
{$IMAGEBASE $400000}
{$IMPLICITBUILD ON}
requires
rtl,
DesignIDE;
contains
MyComponentUnit in 'MyComponentUnit.pas',
MyCompRegUnit in 'MyCompRegUnit.pas';
end.
MyComponentUnit.pas
- 用于组件代码本身的新Delphi单元(File-> New-> Unit)。 Unit声明后退/前进功能的自定义类型。该组件绝对没有任何内容,只是声明了我们可以在设计时通过弹出菜单设置的那种类型的属性。
unit MyComponentUnit;
interface
uses
Classes;
type
TMyComponentDirection = (cdBack, cdForward);
type
TMyComponent=class(TComponent)
private
FDirection: TMyComponentDirection;
published
property Direction: TMyComponentDirection read FDirection write FDirection;
end;
implementation
end.
MyCompRegUnit.pas
,它实现了自定义组件编辑器并注册了组件及其编辑器:
unit MyCompRegUnit;
interface
uses
DesignIntf, DesignEditors, Classes;
type
TMyComponentEditor=class(TComponentEditor)
function GetVerbCount: Integer; override;
function GetVerb(Index: Integer): string; override;
procedure ExecuteVerb(Index: Integer); override;
end;
procedure Register;
implementation
{ TMyComponentEditor }
uses
MyComponentUnit;
// Called when component of this type is right-clicked. It's where
// you actually perform the action. The component editor is passed a reference
// to the component as "Component", which you need to cast to your specific
// component type
procedure TMyComponentEditor.ExecuteVerb(Index: Integer);
begin
inherited;
case Index of
0: (Component as TMyComponent).Direction := cdBack;
1: (Component as TMyComponent).Direction := cdForward;
end;
end;
// Called the number of times you've stated you need in GetVerbCount.
// This is where you add your pop-up menu items
function TMyComponentEditor.GetVerb(Index: Integer): string;
begin
case Index of
0: Result := '&Back';
1: Result := '&Forward';
end;
end;
// Called when the IDE needs to populate the menu. Return the number
// of items you intend to add to the menu.
function TMyComponentEditor.GetVerbCount: Integer;
begin
Result := 2;
end;
procedure Register;
begin
RegisterComponents('TestStuff', [TMyComponent]);
RegisterComponentEditor(TMyComponent, TMyComponentEditor);
end;
end.
您需要保存并构建软件包,然后在项目管理器中右键单击它并选择“安装”。它将在TestStuff
组件面板页面上注册该组件。
全部保存,然后启动一个新的VCL表单应用程序。在Component Palette中,键入TMy
以找到新组件,然后双击它以将其添加到新表单。在表单上右键单击它: