Deleting a dynamically created button a runtime - delphi

I need the user to be able to right click the button and it deletes itself but the following code isn't working
procedure TForm1.Button1Click(Sender: TObject); ////////Creates a new object
var
ExampleButton : TButton;
Begin
ExampleButton := TButton.Create(self); //Creates an object the same as its self
ExampleButton.Parent := self;
//Button properties go here
//Procedures called here
ExampleButton.OnMouseDown := DragOrDelete;
end;
Above creates the button, below I try to delete it
procedure TForm1.DragOrDelete(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
CursorPosition := Mouse.CursorPos; ////Location of mouse
ExampleButtonStartingLocation := TPoint.Create((Sender as Tbutton).Left, (Sender as Tbutton).Top);
if Button = mbRight then
FreeAndNil(TButton);
end;
The error I get is constant object cannot be passed as a var parameter.
Is it because I create numerous TButtons but the program doesn't know which one to refer one.

Well,
FreeAndNil(TButton);
should be
(Sender as TButton).Free; // thanks to DH
But this is not good. The RTL routines that call the event handler will still have a reference to the button, and need to continue accessing it after the event handler exits, so freeing it may cause further problems (also, Sender is not a var parameter, so setting it to nil will have no effect in the caller).
A better option might be to do something like creating a custom message with Sender as the wParam and posting it to the main form.
Edit
To do this you would create a user message, e.g.
const
WM_DELETE_CONTROL = WM_USER +1;
and replace the offending line with
PostMessage( FormMain.WindowHandle, WM_DELETE_CONTROL, WPARAM( Sender ), 0 );
Then create a procedure in your main form to handle the message, e.g.
procedure DestroyButton( var Msg : TMessage); message WM_DELETE_CONTROL;
with a definition like
procedure TForm1.DestroyButton( var Msg : TMessage);
begin
// RemoveControl( TButton( Msg.LParam ));
// correction - thanks to Remy Lebeau
TButton( Msg.WParam ).Free;
end;

You should make two changes there.
1) you should remember which object you created into a variable, living long enough that both procedures can access it.
2) you should destroy that object by the variable, mentioned above
Right now you are trying to destroy just some any random button. But that is hardly what you need! You probably want to destroy exactly the button you was creating, not some another one.
So:
1) FTableButton should be moved out of procedure TForm1.Button1Click and promoted into a variable of TForm1 class.
2) procedure TForm1.Button1Click should check if the button was already created and not create the second, third, forth... buttons.
procedure TForm1.Button1Click(Sender: TObject);
var
TableString : String;
Begin
if nil <> Self.FTableButton then
raise Exception.Create('Dynamic button already exists!!!');
TableString := IntToStr(TableNumber);
Self.FTableButton := TButton.Create(self);
....
Alternatively, you might choose to delete already existing button (if any) before creating a new one. Usually that is not a good idea, but in some specific scenarios it might make sense (when you need to "reset" the button object, to drop old customized object and create a new one with non-customized default properties).
procedure TForm1.Button1Click(Sender: TObject);
var
TableString : String;
Begin
Self.FTableButton.Free; // if there already was a dynamic button - destroy it
TableString := IntToStr(TableNumber);
Self.FTableButton := TButton.Create(self);
....
3) Now that you have that specific button remembered inside form's FTableButton variable you can use it to delete that very specific object.
procedure TForm1.ButtonMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
...
if Button = mbRight then
FreeAndNil( Self.FTableButton );
end;
Now there is another potential issue here - the "cleanup after suicide" issue.
David Heffernan in comments states that you can not delete the TButton from its own event handler. David states that after you exit the TForm1.ButtonMouseDown procedure the just deleted button would (or at least potentially may) do some more after-event actions with itself without recognizing it was already deleted, leading to any potential error, most probably Access Violation of nil dereference kind.
I can agree with half of that claim.
1) using TForm and TButton from VCL library for Windows is safe, because VCL (at least in Delphi XE2 version) was carefully designed to avoid this trap. The button's internal event calling sequence is designed to never directly address itself after the TForm1.ButtonMouseDown exited. So, at least in that narrow case David is not correct and that is safe thing to do.
2) That is called "relying over implementation detail" however. It is bad style because it is fragile. It might work in some specific case but suddenly break from many other reasons.
As soon as you would switch from the standard VCL TButton to some other fancy buttons from any other library ( Dev Express, LMD, TMS, anything ) that code my suddenly broke. Or you might switch form VCL to FMX. Or switch from FMX/Win32 to FMX/Android.
Or maybe just upgrading Delphi to some newer version would have VCL broken in that regard (that is highly unlikely but possible nonetheless).
So, to play safe you have to decouple those two actions: the button's event handling and the process of its deletion. There are many possible ways to do it, but they all demand more or less extra work and some understanding more issues. Those ways I see split into two avenues.
1) Timing would not change, killing the button would be immediate. But it should not be button deleting itself, it should be some other component.
That is the approach I like the most. I think deleting button on right-click is not the good idea. User might click it randomly, by mistake, by sudden twitch of the hand. Doing something as extreme as suddenly deleting button would be way too harsh change for a random erratic action.
I think you should go traditional way here. Right click should open the context menu, and in the menu there should be the command to delete the button. That way, the menu would be deleting the button, not the button itself.
You would need to add the TPopupMenu onto the form having one single element - deleting the button.
object mnu1: TPopupMenu
object mniFreeBM: TMenuItem
Caption = 'Free the button'
OnClick = mniFreeBMClick
end
end
procedure TForm18.mniFreeBMClick(Sender: TObject);
begin
FreeAndNil( Self.btnMenu );
end;
Then you would have to connect that menu to the button.
.....
Self.FTableButton := TButton.Create(self);
// FTableButton.OnMouseUp := ButtonMouseUp; -- no more doing it! bad style!
Self.PopupMenu := mnu1;
mnu1.AutoPopup := True;
.....
Here we go. When user would R-click the button - there would come the menu, asking him if he wants to delete that button. If he does - then menu, not the button itself, would be freeing it. If users cancels the menu - then it was his random action and he want the button to be kept alive.
That is the better approach as I see.
2) other approaches revolve around idea of time delay, they assure that button only asks Delphi to be deleted someday later, but there would be no immediate kill.
Delphi when realizing it was asked to do it, would then delete the button some later time, after OnMouseUp procedure (and probably few other event-handling procedures too) are long executed and exited.
If the application is not heavy loaded with looong heaaavy computations, then that "later" is very very short actually. Most probably the user would never be able to see the difference. For playing safe, the button might also make itself invisible until someone would delete it.
There can be many approaches to do it, but I would list two.
2.1) DSM in his answer outlines Post_Message-centered approach. That is a good solid "old school" code. It is fast. It is well-understood. But it also has some limitations.
a) it only works on Windows. Forget Android, iOS and others. Well, if you only intend to work on Windows then you can just use standard VCL buttons which can suicide safely, at least in Delphi XE2.
b) it needs you to make a lot of boiler plate, like declaring extra procedures and constants.
c) it is unsafe - you have to make hard unchecked typecasts between integers and button pointers. Easy to make mistake typing/refactoring.
d) you need to understand Windows implementation: message loop, VCL place inside that message loop, difference between PostMessage, SendMessage and Perform, etc.
That is not a rocket science. For any "old school" desktop programmer it is easy and well known. Well, if you were one you would not ask such a question.
Another approach would use multi-threading. From performance perfectionism point of view that is abomination. Creating a new thread (quite the expensive operation!) just to call back and ask the button to be deleted - is very inefficient. But - that way you have much less code to write. You can use standard Delphi features that would most probably work with every operating system and every forms/buttons library, in current and future Delphi versions.
The code is like that.
procedure TForm18.btnThreadMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
......
if mbRight = Button then
TThread.CreateAnonymousThread( procedure
begin
TThread.CurrentThread.Synchronize( nil, procedure
begin
FreeAndNil( btnThread );
end
);
end
).Start;
end;
This way when you exit the OnMouseButtonUp the button is not being deleted, there only is incoming request from the temporary thread to delete it. When the form would work that request out may differ, but anyway it would be another event that happens after you safely exited the button's event handler. Unless you used another abomination ProcessMessages but you did not and hopefully you never ever would.

Related

Missing functionality of added Control in another application

I have read this article how to add a button to another application. When the Button is added to the parent application, everything seems OK, but when this Button is added to another app called Labform (TLabForm), the code after click is not executed. I created also a descendant to implement simple behavior after click, but no success:
TButton2 = class (TButton)
public
procedure Click; override;
end;
procedure TButton2.Click;
begin
inherited;
MessageBox(ParentWindow, 'Hello', 'Window', MB_OK);
end;
procedure TForm1.btn1Click(Sender: TObject);
var
Button2 : TButton2 ;
Hand: THandle;
begin
// Hand:= FindWindow('TLabForm', 'Labform'); // button added, but SHOWS NO message after click
Hand:= FindWindow('TForm1', 'Form1'); // button added, and SHOWS message after click
if Hand <> 0 then
begin
Button2 := TButton2.Create(self);
Button2.ParentWindow := hand;
Button2.BringToFront;
end
else
ShowMessage('handle not found');
end;
How to solve it?
thanx
Whilst it is technically possible to do what you want, it is excruciatingly difficult. Raymond Chen wrote about this at some length. The executive summary:
Is it technically legal to have a parent/child or owner/owned relationship between windows from different processes? Yes, it is technically legal. It is also technically legal to juggle chainsaws.
So, you are attempting something with difficulty akin to juggling chainsaws. Unless you have a deep understanding of Win32 you've got no chance of succeeding.
So, if you want to modify the GUI of an existing process, and it's not tractable to do so with code in a different process, what can you do? Well, it follows that you need to execute code inside the target process.
That's easy enough to do with DLL injection. Inject a DLL into the process and modify it's UI from that DLL. Still not trivial. You'll have the best chance of success if you subclass a window by replacing the existing window procedure with one of your own. That will allow you to run your UI modification code in the UI thread.

accessing components of frame1 with frame2, with frame2 being on frame1, in delphi, frames are created dynamically

Originally the question had to be how to access the components in the first place, however I somehow managed to figure it out. I am just learning Delphi so I am prone to dumb and obvious questions. I am also at a stage when I'm not actually writing anything useful, but just messing with random stuff to see how it works and maybe learn something.
Wall of text incoming, i want to explain what i am exploring at the moment...
Basically i have a form1 with a button1, pressing it creates a frame2, that frame2 has a button2, pressing button2 creates a frame3 within frame2 (it being frame3's parent and owner). Each frame has an another freeandnil-button. Upon pressing each button1/2/3, it gets disabled to prevent creating multiple instances. My original problem was that after using freeandnil-button, I couldnt access the button on the previous frame (it worked fine for forms, form1.button1.enabled:=true works fine from within frame2) that got disabled in order to re-enable it (frame2.button1.enabled:=true from within frame3 creates an access violation, I think).
Suppose I write something in the future that requires such communication? So I added an editbox to each frame, with a button on the other to change the editbox text, this is my current working solution:
procedure TFrame2.Button3Click(Sender: TObject);
var i,z:integer;
begin
for i := 0 to ComponentCount - 1 do
if components[i] is tframe3 then
for z := 0 to (components[i] as tframe3).ComponentCount - 1 do
if (components[i] as tframe3).Components[z] is TEdit then
((components[i] as tframe3).Components[z] as TEdit).Text:='ping';
end;
and
procedure TFrame3.Button3Click(Sender: TObject);
var i:integer;
begin
for i := 0 to parent.ComponentCount-1 do
if parent.components[i] is TEdit then
(parent.Components[i] as TEdit).Text:='pong';
end;
If I have a bunch of editboxes or whatever the hell, I suppose I could use Tag property to identify them, however, this much component counting and passing something AS something doesn't really look right or efficient enough to me.
My questions at the moment are: can it be done in a better way? and can someone provide the reasoning why cant I access "parent-frame" components from a "child-frame" in a dumb way (ie: frame2.button1.enabled:=true from within frame3)?
A couple of points:
Controls/Components are usually set to be owned by the form/frame that controls their lifetime and parented to the control that shows them. So when you create a TEdit to sit on a TPanel on a TForm, you would set TForm as the owner and TPanel as the parent of the TEdit. With frames you do the same: the frame is the owner of all controls on it, controls are parented to whatever container on the frame (can be the frame itself) is holding and and is thus reponsible for showing (painting) it.
When you iterate over the children of a control, iterating over Components uses the Owner relation; iterating over Controls uses the Parent relation. So your code above would already do a lot less if it were to iterate over the Controls.
Of course you can reference other controls in a "dumb" way, but you will have to provide for the access method. If you want others (not just child frames) you will at the very least have to declare a method to retrieve that control. Many ways to do this. One is to "ask" the form when you need it (using a method on the form), or have the form set a property on the frame when it is created...
Avoid accessing form's and frame's published properties. They are mainly there for Delphi's streaming system. When you tie your application together using your approach described above it can very soon become one incredibly tangled mess...
Example coming up (sometime this evening), it will take me a bit of time to also explain and I have work to do...
The following example deals only with the ping-pong game between the frames. Freeing any form or frame from one of its own event handlers is not such a good idea. Use the Release method for that as it prevents the form/frame from processing messages after is was freed. (Plenty of questions about this on SO by the way). Also, when you do release a frame from one of its own buttons, you will need to take care that the frame that created it has a chance to nil the references it may have held to that frame otherwise you are setting yourself up for some interesting to debug mayhem. Look into "Notification" and "NotifyControls" and the automatic notification by forms and frames that is sent to their owner/parent so these can remove the control from their components/controls collection. In your example, if you were to release Frame3 from its own "FreeAndNil" button's OnClick event handler, you would have to make sure that the Frame2 responds to the deletion (I think) notification message and nil's any references it holds to Frame3 (besides the ones that will already be cleared automatically in the components/controls collections).
Now, the ping pong game. There are a couple of ways to go about this.
Method 1
The first way is what you already tried with a loop over the components of the other frame. While it certainly is a way to avoid having to "use" the other frame, it is cumbersome and not very concise. Plus when you get more controls on your forms/frames, you will have to add a check on the name to know that you have the correct TEdit. And then you might just as well use the name directly, especially as one frame already has the other frame in its uses clause because it is creating it.
// PingFrame (your Frame2)
uses
...
Pong_fr;
type
TPingFrame = class(TFrame)
...
procedure CreateChildBtnClick(Sender: TObject);
procedure PingPongBtnClick(Sender: TObject);
private
FPong: TPongFrame; // This is the "extra" reference you need to nil when
// freeing the TPongFrame from one of its own event handlers.
...
end;
procedure TPingFrame.CreateChildBtnClick(Sender: TObject);
begin
CreateChildBtn.Enabled := False;
FPong := TPongFrame.Create(Self);
FPong.Parent := ContainerPnl;
FPong.Align := alClient;
end;
procedure TPingFrame.PingPongBtnClick(Sender: TObject);
begin
if Assigned(FPong) then
FPong.Edit1.Text := 'Ping';
end;
And on the other end:
// PongFrame (your Frame3)
type
TPongFrame = class(TFrame)
...
procedure PingPongBtnClick(Sender: TObject);
end;
implementation
uses
Ping_fr;
procedure TPongFrame.PingPong1BtnClick(Sender: TObject);
begin
(Owner as TPingFrame).Edit1.Text := 'Pong called';
end;
This method seems all nice and dandy, but it has drawbacks:
You need to use the unit that holds the TPingFrame (Ping_fr in this example). Not too bad I guess, but... as Ping_fr already uses Pong_fr (the unit holding TPongFrame), you can't have Ping_fr using Pong_fr in the interface section and have Pong_fr using Ping_fr in the interface section as well. Doing so would have Delphi throwing an error because of a circular references. This can be solved by moving one of the uses to the implementation section (as done in the example for the use of Ping_fr in the Pong_fr unit.
A bigger drawback is that there is now a very tight coupling between the two frames. You cannot change the TEdit in either one to another type of control (unless that happens to have a Text property as well) without having to change the code in the other unit as well. Such tight coupling is a cause of major headaches and it is good practice to try and avoid it.
Method 2
One way to decrease the coupling between the frames and allow each frame to change it controls as it sees fit is not to use the controls of another form/frame directly. To do so you declare a method on each frame that the other can call. Each method updates its own controls. And from the OnClick event handlers you no longer access the other frame's controls directly, but you call that method
type
TPingFrame = class(TFrame)
...
public
procedure Ping;
end;
implementation
procedure TPingFrame.PingPongBtnClick(Sender: TObject);
begin
if Assigned(FPong) then
FPong.Ping;
end;
procedure TPingFrame.Ping;
begin
Edit1.Text := 'Someone pinged me';
end;
And on the other end:
type
TPongFrame = class(TFrame)
...
public
procedure Ping;
end;
implementation
procedure TPongFrame.PingPongBtnClick(Sender: TObject);
begin
(Owner as TPingFrame).Ping;
end;
procedure TPongFrame.Ping;
begin
Edit1.Text := 'Someone pinged me';
end;
This is better than Method 1 as it allows both frames to change their controls without having to worryabout "outsiders" referencing them, but still has the drawback of the circular reference that can only be "solved" by moving one "use" to the implementation section.
It is a good practice to try and avoid circular references altogether instead of patching them by moving units to the implementation section's uses clause. A rule of thumb I use is:
Any form/frame may know and use the public interface of the forms/frames it instantiates (though it should avoid the controls in the "default visibility" part of that interface), but no form/frame should not have any knowledge of the specific form/frame that created it.
Method 3
One way of achieving this (there are many) it to use events just like the TButton's OnClick event.
On the TPongFrame side of things you can remove the use of Ping_fr. You no longer need it.
Then you need to declare a property and the field it references and declare a method to fire the event.
type
TPongFrame = class(TFrame)
private
FOnPingPongClicked: TNotifyEvent;
protected
procedure DoPingPongClicked;
public
property OnPingPongClicked: TNotifyEvent
read FOnPingPongClicked write FOnPingPongClicked;
end;
The Ping method stays and its implementation is unchanged. The PingPongBtnClick event handler also stays, but its implementation now becomes:
procedure TPongFrame.PingPongBtnClick(Sender: TObject);
begin
DoPingPongClicked;
end;
procedure TPongFrame.DoPingPongClicked;
begin
if Assigned(FOnPingPongClicked) then
FOnPingPongClicked(Self);
end;
You could put the code from DoPingPongClicked straight in here, but it is a good practice to fire an event in a separate method. It avoids duplicating the exact same code if you would have an event that can be fired from multiple parts of your code. And it also allows descendants (when you get those) to override the "firing" method (you'll have to mark it virtual in the ancestor) and do something specific all the times the event is fired.
On the TPingFrame side of things you need to code a handler for the new event:
type
TPingFrame = class(TFrame)
...
protected
procedure HandleOnPingPongClicked(Sender: TObject);
Note that the signature of this handler needs to be what the TNotifyEvent specifies. And of course you need to ensure that this event handler gets called when the event fires in TPongFrame:
procedure TPingFrame.CreateChildBtnClick(Sender: TObject);
begin
CreateChildBtn.Enabled := False;
FPong := TPongFrame.Create(Self);
FPong.Parent := ContainerPnl;
FPong.Align := alClient;
// Listen to event fired by PongFrame whenever it's PingPingBtn is clicked
FPong.OnPingPongClicked := HandleOnPingPongClicked;
end;
In the handler code you can do what you need to do. It can be general:
procedure TPingFrame.HandleOnPingPongClicked(Sender: TObject);
begin
Edit1.Text := 'OnPingPongClicked event was fired';
end;
And of course you can also use the fact that the event passes a reference to the instance firing the event as well:
procedure TPingFrame.HandleOnPingPongClicked(Sender: TObject);
var
Pong: TPongFrame;
begin
// This checks that Sender actually is a TPongFrame and throws an exception if not
Pong := Sender as TPongFrame;
// Use properties from the Pong instance that was passed in
Edit1.Text := 'OnPingPongClicked event was fired by ' + Pong.Name;
end;
Enjoy!

"pressing" the button of TButtonedEdit using the keyboard

I was just about to replace a TEdit + TButton combination with one TButtonedEdit control but when I tried to test it, I found no way to "press" the (right) button using the keyboard.
I tried Alt+Enter, Alt+Down, Alt+Right, the same keys with Ctrl and a few more key combinations but none of them worked. The VCL sources did not shed any light on this issue either (but hey "professional programmers don't look at the VCL sources" anyway)
Am I missing something?
This is with Delphi 2010 on a Windows XP box, the TButtonedEdit component was introduced in Delphi 2009 IIRC.
Note: I have accepted Andreas Rejbrand's answer because it answers the question. But I have also added my own answer for the benefit of those who might be interested in what I actually implemented.
No, there is no such keyboard shortcut, partly (maybe) because of the ambiguity in which button (the left or right button) the keyboard shortcut should execute.
I always do it like this:
procedure TForm1.ButtonedEdit1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Key = VK_RETURN) and (ssCtrl in Shift) then
ButtonedEdit1RightButtonClick(Sender);
end;
The Ctrl+Enter shortcut is very natural if the button displays a modal dialog (which helps the user fill the edit box), or something similar. If it instead executes a procedure taking the edit text as argument (e.g., an address bar or a search box), Enter alone is more suitable. If the button is a clear button (that clears the edit box), then Escape might be the best shortcut, or possibly no shortcut at all (and then it is a good thing that there is no default shortcut).
The fact that the suitable shortcut depends on the situation also suggests that there should be no default shortcut, I think.
By the way, don't forget to make the TButtonedEdit DoubleBuffered, for otherwise it will flicker way too much.
I have now created an interposer class that looks like this:
interface
{...}
type
TdzButtonedEdit = class(TButtonedEdit)
protected
procedure KeyDown(var _Key: Word; _Shift: TShiftState); override;
public
procedure Loaded; override;
end;
{...}
implementation
{...}
{ TdzButtonedEdit }
procedure TdzButtonedEdit.KeyDown(var _Key: Word; _Shift: TShiftState);
begin
inherited;
if (_Key = VK_RETURN) and (ssCtrl in _Shift) then
if Assigned(OnRightButtonClick) then
OnRightButtonClick(Self);
end;
procedure TdzButtonedEdit.Loaded;
begin
inherited;
if RightButton.Visible and (RightButton.Hint = '') then begin
RightButton.Hint := _('Ctrl+Return to ''click'' right button.');
ShowHint := true;
end;
end;
which I use in the form by declaring:
TButtonedEdit = class(TdzButtonedEdit)
end;
before the form's class declaration.
If I can ever be bothered I'll make it a full blown custom component.
btw: Why did Embarcadero make TEditButton.TGlyph strict private? That's very inconvenient because
normally I would have called RightButton.Glyph.Click rather than OnRightButtonClick.
Given that there is no way to pass the input focus to these embedded buttons, and given that they display glyphs, how could there be keyboard access? How would the user discover it?
On a modal dialog you can press enter and so long as the focus control is not a button, then the default button is pressed and the form closes. That is part of the platform UI standard. Similarly for escape and cancel. Many other controls have standard keyboard access (lists, drop downs, edits etc.)
This is not a standard control and so it would be wrong to impose some default keyboard access beyond what is expected in an edit control. It's fine for the designer to add access because they know what is reasonable on their form, but the VCL designers got it right by not including a default behaviour that would apply to every instance of this control..

How can I Prevent Shortcuts from Colliding/Interacting in Delphi?

I use the standard Cut, Copy, Paste actions on my Main Menu. They have the shortcuts Ctrl-X, Ctrl-C and Ctrl-V.
When I open a modal form, e.g. FindFilesForm.ShowModal, then all the shortcuts work from the form.
But when I open a non-modal form, e.g. FindFilesForm.Show, then the shortcuts do not work.
I would think that those actions should work if the FindFilesForm is the active form. It's modality should have nothing to do with it, or am I wrong in my thinking?
Never-the-less, how can I get the shortcuts to work on a non-modal form?
After Cary's response, I researched it further. It is not a problem with certain controls, e.g. TMemo or TEdit.
But it is for some others. Specifically, the ones where it happens include:
the text in a TComboBox
the text in a TFindDialog
a TElTreeInplaceEdit control, part of LMD's ElPack
I'll see if there are others and add them to the list.
These are all on important Non-Modal forms in my program.
So I still need a solution.
Okay. I really need help with this. So this becomes the first question I am putting a bounty on.
My discussion with Cary that takes place through his answer and the comments there describe my problem in more detail.
And as I mentioned in one of those comments, a related problem seems to be discussed here.
What I need is a solution or a workaround, that will allow the Ctrl-X, Ctrl-C and Ctrl-V to always work in a TComboBox and TFindDialog in a Non-Modal window. If those two get solved, I'm sure my TElTreeInplaceEdit will work as well.
It takes only a couple of minutes to set up an simple test program as Cary describes. Hopefully someone will be able to solve this.
Just be wary that there seems to be something that allows it to work sometimes but not work other times. If I can isolate that in more detail, I'll report it here.
Thanks for any help you can offer me.
Mghie worked very hard to find a solution, and his OnExecute handler combined with his ActionListUpdate handler do the trick. So for his effort, I'm giving him the accepted solution and the bounty points.
But his actionlist update handler is not simple and you need to specify in it all the cases you want to handle. Let's say there's also Ctrl+A for select all or Ctrl-Y for undo you might want. A general procedure would be better.
So if you do come across this question in your search for the answer, try first the answer I supplied that adds an IsShortcut handler. It worked for me and should handle every case and does not need the OnExecute handlers, so is much simpler. Peter Below wrote that code and Uwe Molzhan gets finders fee.
Thanks Cary, mghie, Uwe and Peter for helping me solve this. Couldn't have done it without you. (Maybe I could have, but it might have taken me 6 months.)
OK, first thing first: This has nothing to do with modal or non-modal forms, it is a limitation of the way the Delphi action components work (if you want to call it that).
Let me prove this by a simple example: Create a new application with a new form, drop a TMemo and a TComboBox onto it, and run the application. Both controls will have the system-provided context menu with the edit commands, and will correctly react on them. They will do the same for the menu shortcuts, with the exception of Ctrl + A which isn't supported for the combo box.
Now add a TActionList component with the three standard actions for Cut, Copy and Paste. Things will still work, no changes in behaviour.
Now add a main menu, and add the Edit Menu from the template. Delete all commands but those for Cut, Copy and Paste. Set the corresponding action components for the menu items, and run the application. Observe how the combo box still has the context menu and the commands there still work, but that the shortcuts do no longer work.
The problem is that the standard edit actions have been designed to work with TCustomEdit controls only. Have a look at the TEditAction.HandlesTarget() method in StdActns.pas. Since edit controls in combo boxes, inplace editors in tree controls or edit controls in native dialogs are not caught by this they will not be handled. The menu commands will always be disabled when one of those controls has the focus. As for the shortcuts working only some of the time - this depends on whether the VCL does at some point map the shortcuts to action commands or not. If it doesn't, then they will finally reach the native window procedure and initiate the edit command. In this case the shortcuts will still work. I assume that for modal dialogs the action handling is suspended, so the behaviour is different between modal and non-modal dialogs.
To work around this you can provide handlers for OnExecute of these standard actions. For example for the Paste command:
procedure TMainForm.EditPaste1Execute(Sender: TObject);
var
FocusWnd: HWND;
begin
FocusWnd := GetFocus;
if IsWindow(FocusWnd) then
SendMessage(FocusWnd, WM_PASTE, 0, 0);
end;
and similar handlers for the Cut command (WM_CUT) and the Copy command (WM_COPY). Doing this in the little demo app makes things work again for the combo box. You should try in your application, but I assume this will help. It's a harder task to correctly enable and disable the main menu commands for all native edit controls. Maybe you could send the EM_GETSEL message to check whether the focused edit control has a selection.
Edit:
More info why the behaviour is different between combo boxes on modal vs. non-modal dialogs (analysis done on Delphi 2009): The interesting code is in TWinControl.IsMenuKey() - it tries to find an action component in one of the action lists of the parent form of the focused control which handles the shortcut. If that fails it sends a CM_APPKEYDOWN message, which ultimately leads to the same check being performed with the action lists of the application's main form. But here's the thing: This will be done only if the window handle of the application's main form is enabled (see TApplication.IsShortCut() code). Now calling ShowModal() on a form will disable all other forms, so unless the modal dialog contains itself an action with the same shortcut the native shortcut handling will work.
Edit:
I could reproduce the problem - the key is to somehow get the edit actions become disabled. In retrospect this is obvious, the Enabled property of the actions needs of course to be updated too.
Please try with this additional event handler:
procedure TForm1.ActionList1Update(Action: TBasicAction; var Handled: Boolean);
var
IsEditCtrl, HasSelection, IsReadOnly: boolean;
FocusCtrl: TWinControl;
FocusWnd: HWND;
WndClassName: string;
SelStart, SelEnd: integer;
MsgRes: LRESULT;
begin
if (Action = EditCut1) or (Action = EditCopy1) or (Action = EditPaste1) then
begin
IsEditCtrl := False;
HasSelection := False;
IsReadOnly := False;
FocusCtrl := Screen.ActiveControl;
if (FocusCtrl <> nil) and (FocusCtrl is TCustomEdit) then begin
IsEditCtrl := True;
HasSelection := TCustomEdit(FocusCtrl).SelLength > 0;
IsReadOnly := TCustomEdit(FocusCtrl).ReadOnly;
end else begin
FocusWnd := GetFocus;
if IsWindow(FocusWnd) then begin
SetLength(WndClassName, 64);
GetClassName(FocusWnd, PChar(WndClassName), 64);
WndClassName := PChar(WndClassName);
if AnsiCompareText(WndClassName, 'EDIT') = 0 then begin
IsEditCtrl := True;
SelStart := 0;
SelEnd := 0;
MsgRes := SendMessage(FocusWnd, EM_GETSEL, WPARAM(#SelStart),
LPARAM(#SelEnd));
HasSelection := (MsgRes <> 0) and (SelEnd > SelStart);
end;
end;
end;
EditCut1.Enabled := IsEditCtrl and HasSelection and not IsReadOnly;
EditCopy1.Enabled := IsEditCtrl and HasSelection;
// don't hit the clipboard three times
if Action = EditPaste1 then begin
EditPaste1.Enabled := IsEditCtrl and not IsReadOnly
and Clipboard.HasFormat(CF_TEXT);
end;
Handled := TRUE;
end;
end;
I didn't check for the native edit control being read-only, this could probably be done by adding this:
IsReadOnly := GetWindowLong(FocusWnd, GWL_STYLE) and ES_READONLY <> 0;
Note: I've given mghie the answer as he did a lot of work and his answer is correct, but I have implemented a simpler solution that I added as an answer myself
I posted a link to this question on my blog, and got a suggestion from Uwe Molzhan who is not on StackOverflow. Uwe used to run DelphiPool. He pointed me to this thread at borland.public.delphi.objectpascal:
Action List (mis)behavior.
Tom Alexander who asked the original question in this thread even said:
This behavior occurs usually, but not
all the time. Sometimes after a series
of the above errors, the behavior
starts acting as I would expect.
which is exactly the strange behaviour I've been having that has made this problem near to impossible to track down.
Peter Below responded in that thread that if there are colliding shortcuts, you have to take steps to make sure the active control gets first crack at the shortcut.
Taking his code (which was written for a frames problem) and I just had to modify “ctrl is TCustomFrame” to “ctrl is TControl” and it works perfect. So here is what was needed:
public
Function IsShortcut( var Message: TWMKey): Boolean; override;
Function TMyform.IsShortcut( var Message: TWMKey): Boolean;
Var
ctrl: TWinControl;
comp: TComponent;
i: Integer;
Begin
ctrl := ActiveControl;
If ctrl <> Nil Then Begin
Repeat
ctrl := ctrl.Parent
Until (ctrl = nil) or (ctrl Is TControl);
If ctrl <> nil Then Begin
For i:= 0 To ctrl.componentcount-1 Do Begin
comp:= ctrl.Components[i];
If comp Is TCustomActionList Then Begin
result := TCustomActionList(comp).IsShortcut( message );
If result Then
Exit;
End;
End;
End;
End;
// inherited; { Originally I had this, but it caused multiple executions }
End;
So far this seems to work in all cases for me.
The ironic thing is that it didn't work for Tom Alexander, the original question asker. What he did instead was add a procedure to the FrameEnter event that set the focus to the appropriate grid for the frame. That might imply yet another alternative solution to my question, but I have no need to explore that since Peter's solution works for me.
Also note that Peter includes in his answer an excellent summary of the complex steps of key handling that is worth knowing.
But I do want to now check mghie's edit on his answer and see if that is also a solution.
I created a very simple example with two forms in Delphi 2009 (Update 3 and Update 4 installed) running on Vista 64-bit. The second form, Form2 is displayed non-modally (Form2.Show;). I have a TMemo on Form2. Ctrl-X, Ctrl-V, and Ctrl-C work just fine.
This was before I placed a TMainMenu on Form2.
So, I placed a TMainMenu on the form, and added a TActionList. I create an Edit menu items, and added Copy, Cut, Paste submenu items. I hooked these up to the standard actions EditCopy, EditCut, and EditPaste. Still, everything works fine as before. I can either use the menu items, or the Ctrl-C, Ctrl-X, and Ctrl-V key combinations.
There must be something else going on here.

How to avoid the ding sound when Escape is pressed while a TEdit is focused?

In code I have developed some years ago I have been using this a lot to close the current form on pressing the Escape key at any moment:
procedure TSomeForm.FormKeyPress(Sender: TObject; var Key: Char);
begin
if key = #27 then close;
end;
This behaviour is defined for the TForm. The form's KeyPreview property is be set to True to let the form react to key presses before any other components. It all works perfectly well for the best part of the program, however, when the Escape key is pressed while a TEdit component is focused a sound (a ding sound used by Windows to signify invalid operation) is issued. It still works fine but I have never quite managed to get rid of the sound.
What's the problem with this?
Steps to recreate:
new VCL Forms application, set the form's KeyPreview to true
on the Events tab double-click the onKeyPress event and enter dummy code:
if key=#27 then ;
add a TListBox, TCheckBox, TEdit to the form and run the application
in the application try pressing Esc and NOTHING happens, as specified by the dummy code
focus the TEdit and press Esc. Nothing happens but the sound is played.
You get the ding because you left the ESC in the input. See how Key is a var? Set it to #0 and you eliminate the ding. That removes it from further processing.
procedure TSomeForm.FormKeyPress(Sender: TObject; var Key: Char);
begin
if key = #27 then
begin
key := #0;
close;
end;
end;
KeyPreview is just that, a preview of what will be passed to the controls unless you stop it.
Starting from Jim's answer (thanks Jim) I had to make it work for me. What I needed was to make a dropped down combobox close keeping the selected item and move to the next/previous control when TAB/shift+TAB was pressed. Everytime I did press TAB the annoying sound filled the room. My work arroud was using onKeyDown event to catch the shiftstate, declaring var aShift: boolean; in form's interface and use the following code:
procedure TForm2.StComboKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if ssShift in Shift then aShift := true else aShift := false;
end;
procedure TForm2.StComboKeyPress(Sender: TObject; var Key: Char);
begin
if Key=char(VK_TAB) then
begin
Key := #0;
StCombo.DroppedDown := false;
if aShift
then previousControl.SetFocus
else nextControl.SetFocus;
end;
end;
Using the menu items and setting them to invisible, and using the shortcut, is a quick workaround that I've just stumbled across, but won't work if you need a shortcut that uses a character that is used in the first letter of an existing shortcut: For example for Alt+ENTER, you need to add something like this to the form create procedure:
MainMenu1.Items[0].ShortCut:=TextToShortCut('Alt+e');
However it's probably easier to use TActionList instead, and even though something like Alt+E is not listed you can add it.
It's an old thread... but anyway, here's a far better one: catching Alt-C!
Unlike ESC, Alt-C isn't serviced by KeyPress, so setting Key to #0 in KeyPress doesn't work, and the horrendous "ding!" is issued every time.
After hours of trying, here's the workaround I found:
- create a main menu option to service the request
- set its ShortCut to Alt+C - yes indeed, that is NOT one of the available ShortCut choices(!!)... but it does work anyway!
- do the processing in that menu option's OnClick
- you may even make in "in the background": you may set the menu option's Visible to false - as long as its Enabled stays true, it will be activated by Alt-C even though it will not be visible in the menu.
Hope that may help! And if you have something more elegant, please advise.

Resources