4

How simulate hardware back button press to close application?

I need close the application by code but Application.Terminate, Close, Hide and DisposeOf do not work.

So I thought to simulate hardware back button press to achieve my goal.

Danilo Casa
  • 506
  • 1
  • 9
  • 18
trexios
  • 43
  • 1
  • 4
  • 1
    Do you need to simulate anything? Isn't it enough to close your app? – David Heffernan Sep 23 '13 at 06:39
  • There is currently a glitch in Application.Terminate. Try this: `try formandroid.Hide; Application.MainForm.DisposeOf; except on e:exception do begin Application.MainForm.DisposeOf; end; end; end;` – LU RD Sep 23 '13 at 07:09
  • 1
    @mg30rg he also wrote "close application" which I took to be goal – David Heffernan Sep 23 '13 at 07:38
  • Sorry, I - somehow - did not notice. – mg30rg Sep 23 '13 at 08:01
  • Application.Terminate, Close, Hide and DisposeOf doesn't work. – trexios Sep 23 '13 at 14:28
  • @trexios, edit your question and add what you have tried. – LU RD Sep 23 '13 at 14:51
  • Found a similar thread on embarcadero suggesting to try halt; https://forums.embarcadero.com/thread.jspa?threadID=93120&tstart=0... on a side note, it's interesting to see that a simple thing such as closing the application gets to be so tricky... doesn't sound like delphi, imho. – GabrielF Sep 23 '13 at 19:40
  • 1
    Seems to me that you should understand why you cannot close your application rather than flailing around attempting to fake back button press. – David Heffernan Sep 24 '13 at 06:47

2 Answers2

2
{$IFDEF ANDROID}
    MainActivity.finish;
{$ENDIF}
2

To make your application handle when users press the Back button on their Android device, add an event handler to your form for OnKeyUp, and use the following code within your event handler:

if Key = vkHardwareBack then
begin
// Do whatever you want to do here
Key := 0; // Set Key = 0 if you want to prevent the default action
end;
Max
  • 12,622
  • 16
  • 73
  • 101
Yuliyan
  • 193
  • 2
  • 7