I have a TScrollBox with a bunch of TPanels with some TButtons generated at runtime.
I need to delete the TPanel when one TButton is clicked but doing that in OnClick end in an access violation...
procedure TMainForm.ButanClick(Sender: TObject);
var
vParentPanel: TPanel;
begin
if (string(TButton(Sender).Name).StartsWith('L')) then
begin
TButton(Sender).Caption := 'YARE YARE DAZE';
end
else
begin
vParentPanel := TPanel(TButton(Sender).GetParentComponent());
TheScrollBox.RemoveComponent(vParentPanel);
vParentPanel.Destroy();
// access violation but the panel is removed
end;
end;
procedure TMainForm.Button3Click(Sender: TObject);
var
i: Integer;
vPanel: TPanel;
vButton: TButton;
begin
for i := 0 to 20 do
begin
vPanel := TPanel.Create(TheScrollBox);
vPanel.Align := alTop;
vPanel.Parent := TheScrollBox;
vButton := TButton.Create(vPanel);
vButton.Align := alLeft;
vButton.Parent := vPanel;
vButton.Name := 'L_butan' + IntToStr(i);
vButton.OnClick := ButanClick;
vButton := TButton.Create(vPanel);
vButton.Align := alRight;
vButton.Parent := vPanel;
vButton.Name := 'R_butan' + IntToStr(i);
vButton.OnClick := ButanClick;
end;
end;
You cannot safely destroy the parent TPanel (or the TButton itself) from inside the TButton's OnClick event. The VCL still needs access to the TPanel/TButton for a beat after the event handler exits. So, you need to delay the destruction until after the handler exits. The easiest way to do that is to use TThread.ForceQueue() to call TObject.Free() on the TPanel, eg:
procedure TMainForm.ButanClick(Sender: TObject);
var
vButton: TButton;
begin
vButton := TButton(Sender);
if vButton.Name.StartsWith('L') then
begin
vButton.Caption := 'YARE YARE DAZE';
end
else
begin
TThread.ForceQueue(nil, vButton.Parent.Free);
end;
end;
The TPanel will remove itself from the TScrollBox during its destruction. You do not need to handle that step manually.
Solved with Renate Schaaf answer:
...
const
WM_REMOVEPANEL = WM_USER + 9001;
procedure ButanClick(Sender: TObject);
procedure OnCustomMessage(var Msg: TMessage); message WM_REMOVEPANEL;
...
procedure TMainForm.ButanClick(Sender: TObject);
var
vParentPanel: TPanel;
begin
if (string(TButton(Sender).Name).StartsWith('L')) then
begin
TButton(Sender).Caption := 'YARE YARE DAZE';
end
else
begin
// SendMessage = access violation again because it wait the return
// while PostMessage return istantly
PostMessage(Handle, WM_REMOVEPANEL, 0, THandle(#Sender));
end;
end;
procedure TMainForm.OnCustomMessage(var Msg: TMessage);
var
vButton: TButton;
begin
if (Msg.Msg = WM_REMOVEPANEL) then
begin
vButton := TButton(Pointer(Msg.LParam)^);
ShowMessage(vButton.Name);
TheScrollBox.RemoveComponent(vButton.GetParentComponent());
TPanel(vButton.GetParentComponent()).Destroy();
Msg.Result := 1;
end
else
Msg.Result := 0;
end;
Related
I want to add scroll bars (and/or scroll wheel support) to my existing Delphi application's popup menus, because they are often higher than the screen, and the built in scrolling is not good enough. How to make a popup menu with scrollbar? would be a great solution for me, except that it doesn't support sub-menus, which I absolutely require. The author of that solution hasn't been on StackOverflow since last July, so I don't think he'll reply to my comment. Can anyone see how to modify that code to add support for sub-menus? In case it matters, I need it to work with Delphi 2007.
I share #KenWhite's reservations about how users might receive a huge menu. So apologies to him and readers whose sensibilities the following might offend ;=)
Anyway, I hope the code below shows that in principle, it is straightforward
to create a TreeView based on a TPopUpMenu (see the routine PopUpMenuToTree) which reflects the structure of the PopUpMenu, including sub-items,
and make use of the TreeView's automatic vertical scroll bar. In the code, the
PopUpMenu happens to be on the same form as the TreeView, but that's only for
compactness, of course - the PopUpMenu could be on anothe form entirely.
As mentioned in a comment, personally I would base something like this on a
TVirtualTreeView (http://www.soft-gems.net/index.php/controls/virtual-treeview)
because it is far more customisable than a standard TTreeView.
type
TForm1 = class(TForm)
PopupMenu1: TPopupMenu;
TreeView1: TTreeView; // alClient-aligned
Start1: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure TreeView1Click(Sender: TObject);
private
protected
procedure MenuItemClick(Sender : TObject);
procedure PopUpMenuToTree(PopUpMenu : TPopUpMenu; TreeView : TTreeView);
public
end;
var
Form1: TForm1;
[...]
procedure TForm1.FormCreate(Sender: TObject);
var
Item,
SubItem : TMenuItem;
i,
j : Integer;
begin
// (Over)populate a PopUpMenu
for i := 1 to 50 do begin
Item := TMenuItem.Create(PopUpMenu1);
Item.Caption := 'Item ' + IntToStr(i);
Item.OnClick := MenuItemClick;
PopUpMenu1.Items.Add(Item);
for j := 1 to 5 do begin
SubItem := TMenuItem.Create(PopUpMenu1);
SubItem.Caption := Format('Item %d Subitem %d ', [i, j]);
SubItem.OnClick := MenuItemClick;
Item.Add(SubItem);
end;
end;
// Populate a TreeView from the PopUpMenu
PopUpMenuToTree(PopUpMenu1, TreeView1);
end;
procedure TForm1.MenuItemClick(Sender: TObject);
var
Item : TMenuItem;
begin
if Sender is TMenuItem then
Caption := TMenuItem(Sender).Caption + ' clicked';
end;
procedure TForm1.PopUpMenuToTree(PopUpMenu: TPopUpMenu;
TreeView: TTreeView);
// Populates the TreeView with the Items in the PopUpMenu
var
i : Integer;
Item : TMenuItem;
RootNode : TTreeNode;
procedure AddItem(Item : TMenuItem; ParentNode : TTreeNode);
var
Node : TTreeNode;
j : Integer;
begin
Node := TreeView.Items.AddChildObject(ParentNode, Item.Caption, Item);
for j := 0 to Item.Count - 1 do begin
AddItem(Item.Items[j], Node);
end;
end;
begin
TreeView.Items.BeginUpdate;
TreeView.Items.Clear;
try
for i := 0 to PopUpMenu.Items.Count - 1 do begin
AddItem(PopUpMenu.Items[i], Nil);
end;
finally
TreeView.Items.EndUpdate;
end;
end;
procedure TForm1.TreeView1Click(Sender: TObject);
var
Node : TTreeNode;
Item : TMenuItem;
begin
if Sender is TTreeView then begin
Node := TTreeView(Sender).Selected;
Item := TMenuItem(Node.Data);
Item.Click;
end;
end;
Here's what I have done, by merging How to make a popup menu with scrollbar?, MartynA's code, and some of my own:
unit PopupUnit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
StdCtrls, Menus, ComCtrls;
type
TPopupMode = (pmStandard, pmCustom);
TPopupMenu = class(Menus.TPopupMenu)
private
FPopupForm: TForm;
FPopupMode: TPopupMode;
public
constructor Create(AOwner: TComponent); override;
procedure Popup(X, Y: Integer); override;
property PopupForm: TForm read FPopupForm write FPopupForm;
property PopupMode: TPopupMode read FPopupMode write FPopupMode;
end;
type
TPopupForm = class(TForm)
private
FPopupForm: TForm;
FPopupMenu: TPopupMenu;
FTreeView: TTreeView;
procedure DoResize;
procedure TreeViewClick(Sender: TObject);
procedure TreeViewCollapsedOrExpanded(Sender: TObject; Node: TTreeNode);
procedure TreeViewKeyPress(Sender: TObject; var Key: Char);
procedure WMActivate(var AMessage: TWMActivate); message WM_ACTIVATE;
protected
procedure CreateParams(var Params: TCreateParams); override;
public
constructor Create(AOwner: TComponent; APopupForm: TForm;
APopupMenu: TPopupMenu); reintroduce;
end;
var
PopupForm: TPopupForm;
implementation
{$R *.dfm}
{ TPopupForm }
constructor TPopupForm.Create(AOwner: TComponent; APopupForm: TForm;
APopupMenu: TPopupMenu);
procedure AddItem(Item : TMenuItem; ParentNode : TTreeNode);
var
I : Integer;
Node : TTreeNode;
begin
if Item.Caption <> '-' then begin
Node := FTreeView.Items.AddChildObject(ParentNode, Item.Caption, Item);
Node.ImageIndex := Item.ImageIndex;
for I := 0 to Item.Count - 1 do begin
AddItem(Item.Items[I], Node);
end;
end;
end;
var
I: Integer;
begin
inherited Create(AOwner);
BorderStyle := bsNone;
FPopupForm := APopupForm;
FPopupMenu := APopupMenu;
FTreeView := TTreeView.Create(Self);
FTreeView.Parent := Self;
FTreeView.Align := alClient;
FTreeView.BorderStyle := bsSingle;
FTreeView.Color := clMenu;
FTreeView.Images := FPopupMenu.Images;
FTreeView.ReadOnly := TRUE;
FTreeView.ShowHint := FALSE;
FTreeView.ToolTips := FALSE;
FTreeView.OnClick := TreeViewClick;
FTreeView.OnCollapsed := TreeViewCollapsedOrExpanded;
FTreeView.OnExpanded := TreeViewCollapsedOrExpanded;
FTreeView.OnKeyPress := TreeViewKeyPress;
FTreeView.Items.BeginUpdate;
try
FTreeView.Items.Clear;
for I := 0 to FPopupMenu.Items.Count - 1 do
begin
AddItem(FPopupMenu.Items[I], NIL);
end;
finally
FTreeView.Items.EndUpdate;
end;
DoResize;
end;
procedure TPopupForm.CreateParams(var Params: TCreateParams);
begin
inherited;
Params.WindowClass.Style := Params.WindowClass.Style or CS_DROPSHADOW;
end;
procedure TPopupForm.DoResize;
const
BORDER = 2;
var
ItemRect, TVRect : TRect;
MF : TForm;
Node : TTreeNode;
begin
TVRect := Rect(0, 0, 0, 0);
Node := FTreeView.Items[0];
while Node <> NIL do begin
ItemRect := Node.DisplayRect(TRUE);
ItemRect.Right := ItemRect.Right + FTreeView.Images.Width + 1;
if ItemRect.Left < TVRect.Left then
TVRect.Left := ItemRect.Left;
if ItemRect.Right > TVRect.Right then
TVRect.Right := ItemRect.Right;
if ItemRect.Top < TVRect.Top then
TVRect.Top := ItemRect.Top;
if ItemRect.Bottom > TVRect.Bottom then
TVRect.Bottom := ItemRect.Bottom;
Node := Node.GetNextVisible;
end;
MF := Application.MainForm;
if Top + TVRect.Bottom - TVRect.Top > MF.Top + MF.ClientHeight then begin
TVRect.Bottom := TVRect.Bottom -
(Top + TVRect.Bottom - TVRect.Top - (MF.Top + MF.ClientHeight));
end;
if Left + TVRect.Right - TVRect.Left > MF.Left + MF.ClientWidth then begin
TVRect.Right := TVRect.Right -
(Left + TVRect.Right - TVRect.Left - (MF.Left + MF.ClientWidth));
end;
ClientHeight := TVRect.Bottom - TVRect.Top + BORDER * 2;
ClientWidth := TVRect.Right - TVRect.Left + BORDER * 2;
end;
procedure TPopupForm.TreeViewClick(Sender: TObject);
var
Node : TTreeNode;
Item : TMenuItem;
begin
if Sender is TTreeView then begin
Node := TTreeView(Sender).Selected;
if assigned(Node) then begin
Item := TMenuItem(Node.Data);
if assigned(Item.OnClick) then begin
Item.Click;
Close;
end;
end;
end;
end;
procedure TPopupForm.TreeViewCollapsedOrExpanded(Sender: TObject;
Node: TTreeNode);
begin
DoResize;
end;
procedure TPopupForm.TreeViewKeyPress(Sender: TObject; var Key: Char);
begin
if Ord(Key) = VK_RETURN then begin
TreeViewClick(Sender);
end
else if Ord(Key) = VK_ESCAPE then begin
Close;
end;
end;
procedure TPopupForm.WMActivate(var AMessage: TWMActivate);
begin
SendMessage(FPopupForm.Handle, WM_NCACTIVATE, 1, 0);
inherited;
if AMessage.Active = WA_INACTIVE then
Release;
FTreeView.Select(NIL, []);
end;
{ TPopupMenu }
constructor TPopupMenu.Create(AOwner: TComponent);
begin
inherited;
FPopupMode := pmStandard;
end;
procedure TPopupMenu.Popup(X, Y: Integer);
begin
case FPopupMode of
pmCustom:
with TPopupForm.Create(nil, FPopupForm, Self) do
begin
Top := Y;
Left := X;
Show;
end;
pmStandard: inherited;
end;
end;
end.
I have a form that has a list of useful procedures that I have created, that I often use in every project. I am adding a procedure that makes it simple to add a click-able image over where would be the TAccessory of a TListBoxItem. The procedure intakes the ListBox currently, but I would also need it to intake which procedure to call for the OnClick Event for the image.. Here is my existing code:
function ListBoxAddClick(ListBox:TListBox{assuming I need to add another parameter here!! but what????}):TListBox;
var
i : Integer;
Box : TListBox;
BoxItem : TListBoxItem;
Click : TImage;
begin
i := 0;
Box := ListBox;
while i <> Box.Items.Count do begin
BoxItem := Box.ListItems[0];
BoxItem.Selectable := False;
Click := Timage.Create(nil);
Click.Parent := BoxItem;
Click.Height := BoxItem.Height;
Click.Width := 50;
Click.Align := TAlignLayout.alRight;
Click.TouchTargetExpansion.Left := -5;
Click.TouchTargetExpansion.Bottom := -5;
Click.TouchTargetExpansion.Right := -5;
Click.TouchTargetExpansion.Top := -5;
Click.OnClick := // this is where I need help
i := +1;
end;
Result := Box;
end;
The desired procedure would be defined in the form that is calling this function.
Since the OnClick event is of type TNotifyEvent you should define a parameter of that type. Look at this (I hope self-explaining) example:
type
TForm1 = class(TForm)
Button1: TButton;
ListBox1: TListBox;
procedure Button1Click(Sender: TObject);
private
procedure TheClickEvent(Sender: TObject);
end;
implementation
procedure ListBoxAddClick(ListBox: TListBox; OnClickMethod: TNotifyEvent);
var
Image: TImage;
begin
Image := TImage.Create(nil);
// here is assigned the passed event method to the OnClick event
Image.OnClick := OnClickMethod;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
// here the TheClickEvent event method is passed
ListBoxAddClick(ListBox1, TheClickEvent);
end;
procedure TForm1.TheClickEvent(Sender: TObject);
begin
// do something here
end;
I am writing a class which will map a large legacy application's TMainMenu hierarchy to TActionMainMenuBar items.
The most important method, which borrows heavily from a EDN CodeCentralC article by Steve Trevethen, looks like this. I apologize for the length, but this really is probably the shortest length of code I could meaningfully show in this case:
procedure TMainMenuSkin.DoLoadMenu(
ActionList: TCustomActionList;
Clients: TActionClients;
AMenu: TMenuItem;
SetActionList: Boolean = True;
bRecurseFlag:Boolean = False);
var
I: Integer;
J: Integer;
AC: TActionClientItem;
ca : TCustomAction;
newAction : TSkinnedMenuAction;
aci:TActionClientItem;
submenuitem : TMEnuItem;
procedure PopulateNodeFromMenuItem(menuitem:TMenuItem);
begin
newAction := TSkinnedMenuAction.Create(Application.MainForm);
menuitem.FreeNotification(newAction);
newAction.FMenuItem := menuitem;
newAction.Name := 'action_'+newAction.FMenuItem.Name;
FNewMenuActions.Add(newAction);
newAction.ActionList := ActionManager;
newAction.Tag := menuitem.Tag;
ca := newAction;
ca.ImageIndex := menuitem.ImageIndex;
ca.HelpContext := menuitem.HelpContext;
ca.Visible := menuitem.Visible;
ca.Checked := menuitem.Checked;
ca.Caption := menuitem.Caption;
ca.ShortCut := menuitem.ShortCut;
ca.Enabled := menuitem.Enabled;
ca.AutoCheck := menuitem.AutoCheck;
ca.Checked := menuitem.Checked;
ca.GroupIndex := menuitem.GroupIndex;
AC.ImageIndex := menuitem.ImageIndex;
AC.ShortCut := menuitem.ShortCut;
AC.Action := newAction;
end;
begin
if not Assigned(AMenu) then
exit;
AMenu.RethinkHotkeys;
AMenu.RethinkLines;
Clients.AutoHotKeys := False;
for I := 0 to AMenu.Count - 1 do
begin
AC := Clients.Add;
AC.Caption := AMenu.Items[I].Caption;
// Assign the Tag property to the TMenuItem for reference
AC.Tag := Integer(AMenu.Items[I]);
AC.Action := TContainedAction(AMenu.Items[I].Action);
AC.Visible := AMenu.Items[I].Visible;
// original sample code only created placeholders for submenus. I want to populate
// fully because I need the actions and their keyboard shortcuts to exist.
submenuitem := AMenu.Items[I];
if submenuitem.Count > 0 then
begin
if not bRecurseFlag then
AC.Items.Add // old busted way to work
else
begin
// How do I recursively populate the Action Clients menu?
DoLoadMenu(ActionList, AC.ActionClients, submenuitem, true);
end;
end
else
if ((AMenu.Items[I].Caption <> '') and (AMenu.Items[I].Action = nil) and
(AMenu.Items[I].Caption <> '-')) then
begin
PopulateNodeFromMenuItem( AMenu.Items[I] );
end;
AC.Caption := AMenu.Items[I].Caption;
AC.ImageIndex := AMenu.Items[I].ImageIndex;
AC.HelpContext := AMenu.Items[I].HelpContext;
AC.ShortCut := AMenu.Items[I].ShortCut;
AC.Visible := AMenu.Items[I].Visible;
end;
end;
The most important line above is this one, and it's also the one
that is wrong:
DoLoadMenu(ActionList, AC.ActionClients, submenuitem, true);
If the code is written like that, then I get all the menu items displayed in a flattened form. So I need something like AC.GetMeSubItems.ActionClients in the line above,
but I can't figure out what it is. AC is of type TActionClientItem and is a toolbar button itself also created at runtime.
What I can't figure out for the life of me is, if I need to populate the Actions list and the menu items all at once, recursively, how do I do it? Perhaps my thinking is constrained by the sample code I started out with here. It seems like I'm one line of code away from knowing how to do this.
I have a feeling that I'm just not understanding very well the complex hiearchical relationships of the various classes I'm messing with here.
Update: The following SEEMS to work, but I don't trust myself.
aci := AC.Items.Add;
DoLoadMenu(ActionList, aci.Items, submenuitem, true);
Here's some code that I once wrote or found somewhere and which seems to do what you want to achieve: it is a converter class which copies the items of a Mainmenu to an ActionMainMenubar. It has some issues, but hopefully you can catch the point how it works.
The component assumes that you have a completed MainMenu on a form. You also need a TActionManager and an empty TActionMainMenubar. You create an instance of the TActionbarConverter in the OnCreate event of the MainForm, and assign its properties correspondingly, something like this:
procedure TForm1.FormCreate(Sender: TObject);
begin
with TActionbarConverter.Create(self) do begin
Form := self;
ActionManager := Actionmanager1;
ActionMainMenubar := ActionMainmenubar1;
end;
end;
You can change properties of the ActionManager, or use your own ColorMap to modify the appearance.
I hope that I don't get banned here by posting almost 400 lines of code here (don't know how to upload files...).
unit ActnbarCnv;
interface
uses
Classes, Menus, Forms, ComCtrls, ActnList, ActnMan, ActnMenus,
StdStyleActnCtrls, XPStyleActnCtrls;
type
TActionbarConverter = class(TComponent)
private
FForm : TCustomForm;
FMainMenu : TMainMenu;
FMainMenuToolbar : TToolbar;
FActionManager : TActionManager;
FActionMainMenubar : TActionMainMenubar;
FNewMenuActions : TList;
procedure ActionMainMenuBar_ExitMenuLoop(Sender:TCustomActionMenuBar;
Cancelled: Boolean);
procedure ActionMainMenubar_Popup(Sender:TObject; Item:TCustomActionControl);
procedure SetActionMainMenubar(Value:TActionMainMenubar);
procedure SetActionManager(Value:TActionManager);
procedure SetForm(Value:TCustomForm);
protected
procedure AnalyzeForm;
procedure Loaded; override;
procedure LoadMenu(ActionList: TCustomActionList; Clients: TActionClients;
AMenu: TMenuItem; SetActionList: Boolean = True);
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure ProcessMenu;
procedure UpdateActionMainMenuBar(Menu: TMenu);
public
constructor Create(AOwner:TComponent); override;
destructor Destroy; override;
procedure Update;
published
property Form : TCustomForm read FForm write SetForm;
property ActionManager : TActionManager read FActionManager write SetActionManager;
property ActionMainMenubar : TActionMainMenubar read FActionMainMenubar write SetActionMainMenubar;
end;
//==============================================================================
implementation
//==============================================================================
uses
SysUtils;
//==============================================================================
{ TABMenuAction -
This class is a special ActionBand menu action that stores the TMenuItem
that it is associated with so that if it is executed it can actually call the
TMenuItem.Click method simulating an actual click on the TMenuItem itself. }
type
TABMenuAction = class(TCustomAction)
private
FMenuItem: TMenuItem;
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
destructor Destroy; override;
procedure ExecuteTarget(Target: TObject); override;
function HandlesTarget(Target: TObject): Boolean; override;
end;
//------------------------------------------------------------------------------
destructor TABMenuAction.Destroy;
begin
if Assigned(FMenuItem) then FMenuItem.RemoveFreeNotification(Self);
inherited;
end;
//------------------------------------------------------------------------------
procedure TABMenuAction.ExecuteTarget(Target: TObject);
begin
if Assigned(FMenuItem) then FMenuItem.Click;
end;
//------------------------------------------------------------------------------
function TABMenuAction.HandlesTarget(Target: TObject): Boolean;
begin
Result := True;
end;
//------------------------------------------------------------------------------
procedure TABMenuAction.Notification(AComponent: TComponent; Operation: TOperation);
begin
if (Operation = opRemove) and (AComponent = FMenuItem)
then FMenuItem := nil;
end;
//------------------------------------------------------------------------------
// TActionbarConverter
//------------------------------------------------------------------------------
constructor TActionbarConverter.Create(AOwner:TComponent);
begin
inherited Create(AOwner);
FNewMenuActions := TList.Create;
if (AOwner is TCustomForm) then SetForm(TCustomForm(AOwner));
end;
//------------------------------------------------------------------------------
destructor TActionbarConverter.Destroy;
begin
FNewMenuActions.Free;
inherited Destroy;
end;
//------------------------------------------------------------------------------
procedure TActionbarConverter.ActionMainMenuBar_ExitMenuLoop(Sender:TCustomActionMenuBar;
Cancelled: Boolean);
var
I: Integer;
AnAction: TObject;
begin
// Clear the top level menu sub item and add a single dummy item which
// will cause them to be regenerated on the next menu loop. This is done
// because the IDE's menus can be very dynamic and this ensures that the
// menus will always be up-to-date.
for I := 0 to FActionManager.ActionBars[0].Items.Count - 1 do begin
FActionManager.ActionBars[0].Items[I].Items.Clear;
FActionManager.ActionBars[0].Items[I].Items.Add;
end;
// Any menuitems not linked to an action had one dynamically created for them
// during the menu loop so now we need to destroy them
while FNewMenuActions.Count > 0 do begin
AnAction := TObject(FNewMenuActions.Items[0]);
AnAction.Free;
FNewMenuActions.Delete(0);
end;
end;
//------------------------------------------------------------------------------
procedure TActionbarConverter.ActionMainMenubar_Popup(Sender:TObject;
Item: TCustomActionControl);
begin
// If the tag is not zero then we've already populated this submenu...
if Item.ActionClient.Items[0].Tag <> 0 then exit;
// ...otherwise this is the first visit to this submenu and we need to
// populate the actual ActionClients collection.
if Assigned(TMenuItem(Item.ActionClient.Tag).OnClick) then
TMenuItem(Item.ActionClient.Tag).OnClick(TMenuItem(Item.ActionClient.Tag));
Item.ActionClient.Items.Clear;
TMenuItem(Item.ActionClient.Tag).RethinkHotkeys;
LoadMenu(FActionManager, Item.ActionClient.Items, TMenuItem(Item.ActionClient.Tag), False);
end;
//------------------------------------------------------------------------------
procedure TActionbarConverter.AnalyzeForm;
var
i : integer;
begin
FMainMenu := nil;
FMainMenuToolbar := nil;
if Assigned(FForm) then begin
for i:=0 to FForm.ComponentCount-1 do
if (FForm.Components[i] is TMainMenu) then begin
FMainMenu := FForm.Components[i] as TMainMenu;
break;
end;
for i:=0 to FForm.ComponentCount-1 do
if (FForm.Components[i] is TToolbar) then begin
FMainMenuToolbar := FForm.Components[i] as TToolbar;
if FMainMenuToolbar.Menu = FMainMenu
then break
else FMainMenuToolbar := nil;
end;
end;
ProcessMenu;
end;
//------------------------------------------------------------------------------
procedure TActionbarConverter.Loaded;
begin
AnalyzeForm;
end;
//------------------------------------------------------------------------------
procedure TActionbarConverter.LoadMenu(ActionList: TCustomActionList;
Clients: TActionClients; AMenu: TMenuItem; SetActionList: Boolean = True);
{ This method dynamically builds the ActionBand menu from an existing
TMenuItem. }
var
I: Integer;
AC: TActionClientItem;
begin
AMenu.RethinkHotkeys;
AMenu.RethinkLines;
// Use the existing hotkeys from the TMenuItem
Clients.AutoHotKeys := False;
for I := 0 to AMenu.Count - 1 do begin
AC := Clients.Add;
AC.Caption := AMenu.Items[I].Caption;
// Assign the Tag property to the TMenuItem for reference
AC.Tag := Integer(AMenu.Items[I]);
AC.Action := TContainedAction(AMenu.Items[I].Action);
AC.Visible := AMenu.Items[I].Visible;
// If the TMenuItem has subitems add an ActionClient placeholder.
// Submenus are only populated when the user selects the parent item of the
// submenu.
if AMenu.Items[I].Count > 0 then
AC.Items.Add // Add a dummy indicating this item can/should be dynamically built
else
if (AMenu.Items[I].Caption <> '')
and (AMenu.Items[I].Action = nil)
and (AMenu.Items[I].Caption <> '-')
then begin
// The TMenuItem is not connected to an action so dynamically create
// an action.
AC.Action := TABMenuAction.Create(self); //Application.MainForm);
AMenu.Items[I].FreeNotification(AC.Action);
TABMenuAction(AC.Action).FMenuItem := AMenu.Items[I];
FNewMenuActions.Add(AC.Action);
AC.Action.ActionList := FActionManager;
AC.Action.Tag := AMenu.Items[I].Tag;
TCustomAction(AC.Action).ImageIndex := AMenu.Items[I].ImageIndex;
TCustomAction(AC.Action).HelpContext := AMenu.Items[I].HelpContext;
TCustomAction(AC.Action).Visible := AMenu.Items[I].Visible;
TCustomAction(AC.Action).Checked := AMenu.Items[I].Checked;
TCustomAction(AC.Action).Caption := AMenu.Items[I].Caption;
TCustomAction(AC.Action).ShortCut := AMenu.Items[I].ShortCut;
TCustomAction(AC.Action).Enabled := AMenu.Items[I].Enabled;
TCustomAction(AC.Action).AutoCheck := AMenu.Items[I].AutoCheck;
TCustomAction(AC.Action).Checked := AMenu.Items[I].Checked;
TCustomAction(AC.Action).GroupIndex := AMenu.Items[I].GroupIndex;
AC.ImageIndex := AMenu.Items[I].ImageIndex;
AC.ShortCut := AMenu.Items[I].ShortCut;
end;
AC.Caption := AMenu.Items[I].Caption;
AC.ImageIndex := AMenu.Items[I].ImageIndex;
AC.HelpContext := AMenu.Items[I].HelpContext;
AC.ShortCut := AMenu.Items[I].ShortCut;
AC.Visible := AMenu.Items[I].Visible;
end;
end;
//------------------------------------------------------------------------------
procedure TActionbarConverter.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation = opRemove) then
if (AComponent=FForm) then SetForm(nil);
end;
//------------------------------------------------------------------------------
procedure TActionbarConverter.ProcessMenu;
begin
if FMainMenu <> nil then begin
if FMainMenutoolbar <> nil then begin
FMainMenutoolbar.Menu := nil;
FMainMenutoolbar.Visible := false;
end;
FForm.Menu := nil;
if FActionManager=nil then begin
FActionManager := TActionManager.Create(self);
// FActionManager.Style := XPStyle;
end else
FActionManager.Actionbars.Clear;
FActionManager.Images := FMainMenu.Images;
FActionManager.Actionbars.Add;
if FActionMainMenubar=nil then begin
FActionMainMenubar := TActionMainMenubar.Create(self);
if (FMainMenuToolbar <> nil)
then FActionMainMenubar.Parent := FMainMenuToolbar.Parent
else FActionMainMenubar.Parent := FForm;
end;
FActionMainMenubar.ActionManager := FActionManager;
FActionMainMenubar.OnPopup := ActionMainMenubar_Popup;
FActionMainMenubar.OnExitMenuLoop := ActionMainMenubar_ExitMenuLoop;
UpdateActionMainMenubar(FMainMenu);
end;
end;
//------------------------------------------------------------------------------
procedure TActionbarConverter.SetActionMainmenubar(Value:TActionMainMenubar);
begin
if Value=nil then begin
FActionMainMenubar := TActionMainMenubar.Create(self);
if FMainmenuToolbar <> nil
then FActionMainMenubar.Parent := FMainMenuToolbar.Parent
else FActionMainMenubar.Parent := FForm;
end else begin
FActionMainMenubar.Free;
FActionMainMenubar := value;
end;
Update;
end;
//------------------------------------------------------------------------------
procedure TActionbarConverter.SetActionManager(value:TActionManager);
begin
if Value = nil then begin
FActionManager := TActionManager.Create(self);
FActionManager.Style := XPStyle;
end else begin
FActionManager := value;
// if FMainMenu <> nil then FActionManager.Images := FMainMenu.Images;
end;
Update;
end;
//------------------------------------------------------------------------------
procedure TActionbarConverter.SetForm(value:TCustomForm);
begin
if FForm <> Value then begin
FForm := Value;
AnalyzeForm;
end;
end;
//------------------------------------------------------------------------------
procedure TActionbarConverter.Update;
begin
AnalyzeForm;
end;
//------------------------------------------------------------------------------
procedure TActionbarConverter.UpdateActionMainMenuBar(Menu: TMenu);
{ This routine should probably also check for Enabled state although it would
be very wierd to have a top level menu disabled. }
function RefreshItems: Boolean;
var
I: Integer;
begin
Result := FMainMenu.Items.Count <> FActionManager.ActionBars[0].Items.Count;
if not Result then
for I := 0 to FMainMenu.Items.Count - 1 do
if AnsiCompareText(
FMainMenu.Items[I].Caption,
FActionManager.ActionBars[0].Items[I].Caption ) <> 0
then begin
Result := True;
break;
end;
end;
begin
if not (csLoading in FActionManager.ComponentState) and RefreshItems
then begin
// Clear any existing items and repopulate the TActionMainMenuBar
FActionManager.ActionBars[0].Items.Clear;
FActionManager.ActionBars[0].ActionBar := nil;
LoadMenu(FActionManager, FActionManager.ActionBars[0].Items, FMainMenu.Items);
FActionManager.ActionBars[0].ActionBar := FActionMainMenuBar;
// Update the size of the main menu
with FActionMainMenuBar do
SetBounds(
0,
0,
Controls[ControlCount-1].BoundsRect.Right + 2 + FActionMainMenuBar.HorzMargin,
Height
);
end;
end;
end.
How to delete created labels. I tried FindComponent but failed , what I have to do? should I set there parent to other component like TPanel or what?
procedure TForm1.Button1Click(Sender: TObject);
var
lblLink: TLabel;
begin
for i := 0 to stringtList.Count-1 do
begin
lblLink := TLabel.create(self);
with lblLink do
begin
name:='lblLink'+inttostr(i);
caption:inttostr(i);
Parent := self;
font.style := [fsUnderline];
cursor := crHandPoint;
color := clBlue;
font.Color := clBlue;
end;
end;
end;
You can iterate over the Components property, then check for the name of the component and finally free the component.
Var
LIndex : Integer;
LComponent : TComponent;
begin
for LIndex := ComponentCount-1 downto 0 do
if StartsText('lblLink',Components[LIndex].Name) then
begin
LComponent:=Components[LIndex];
FreeAndNil(LComponent);
end;
end;
You don't have to free it. You gave the responsibility to free it to the form with lblLink := TLabel.create(self);. The form will free the label when the form is freed.
However, with that being said, you can free it by looping through the form's Components array:
procedure TForm1.DeleteLabel(const LabelName: string);
var
i: Integer;
begin
for i := ComponentCount - 1 downto 0 do
begin
if Components[i] is TLabel then
if Components[i].Name = LabelName then
begin
Components[i].Free;
Break;
end;
end;
end;
You assigned both an Owner and a Parent to each TLabel, so techncally you do not need to free them at all. Both the Owner and the Parent will handle that for you. However, if you wanted to free them earlier, you could loop through the Owner's Components list or the Parent's Controls list, hunting for the labels manually. A better option is to keep your own list of the labels you create, then you can loop through that list when needed, eg:
type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
...
private
Labels: TList;
procedure FreeLabels;
...
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Labels := TList.Create;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
Labels.Free;
end;
procedure TForm1.FreeLabels;
var
I: Integer;
begin
for I := 0 to Labels.Count-1 do
TLabel(Labels[I]).Free;
Labels.Clear;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
lblLink : TLabel;
...
begin
...
for I := 0 to StringList.Count-1 do
begin
lblLink := TLabel.Create(Self);
try
with lblLink do
begin
Name := 'lblLink' + IntToStr(i);
Parent := Self;
Caption := IntToStr(i);
Font.Style := [fsUnderline];
Cursor := crHandPoint;
Color := clBlue;
Font.Color := clBlue;
end;
Labels.Add(lblLink);
except
lblLink.Free;
raise;
end;
end;
end;
As the title says, I'd like a component (say, a label) to be notified when it's parent (say, a panel) receives and loses focus. I wandered a bit in Delphi source, in hope of using TControl.Notify, but it's only used to notify child controls of some property changes like font and color. Any suggestions?
Whenever the active control in an application changes, a CM_FOCUSCHANGED message is broadcast to all controls. Simply intercept it, and act accordingly.
Also, I assumed that by when it's parent (say, a panel) receives and loses focus you mean whenever a (nested) child control on that parent/panel receives or loses focus.
type
TLabel = class(StdCtrls.TLabel)
private
function HasCommonParent(AControl: TWinControl): Boolean;
procedure CMFocusChanged(var Message: TCMFocusChanged);
message CM_FOCUSCHANGED;
end;
procedure TLabel.CMFocusChanged(var Message: TCMFocusChanged);
const
FontStyles: array[Boolean] of TFontStyles = ([], [fsBold]);
begin
inherited;
Font.Style := FontStyles[HasCommonParent(Message.Sender)];
end;
function TLabel.HasCommonParent(AControl: TWinControl): Boolean;
begin
Result := False;
while AControl <> nil do
begin
if AControl = Parent then
begin
Result := True;
Break;
end;
AControl := AControl.Parent;
end;
end;
If you don't like to subclass TJvGradientHeader, then it is possible to design this generically by the use of Screen.OnActiveControlChange:
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
FHeaders: TList;
procedure ActiveControlChanged(Sender: TObject);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
FHeaders := TList.Create;
FHeaders.Add(Label1);
FHeaders.Add(Label2);
Screen.OnActiveControlChange := ActiveControlChanged;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
FHeaders.Free;
end;
function HasCommonParent(AControl: TWinControl; AMatch: TControl): Boolean;
begin
Result := False;
while AControl <> nil do
begin
if AControl = AMatch.Parent then
begin
Result := True;
Break;
end;
AControl := AControl.Parent;
end;
end;
procedure TForm1.ActiveControlChanged(Sender: TObject);
const
FontStyles: array[Boolean] of TFontStyles = ([], [fsBold]);
var
I: Integer;
begin
for I := 0 to FHeaders.Count - 1 do
TLabel(FHeaders[I]).Font.Style :=
FontStyles[HasCommonParent(Screen.ActiveControl, TLabel(FHeaders[I]))];
end;
Note that I chose TLabel to demonstrate this works also for TControl derivatives.