Firemonkey里触发home按键被按下的事件
吾八哥我最近在使用Delphi里的Firemonkey平台写一个叫“由由密码管家”的APP工具,是跨多平台的,如ios/android/windows/macOs。由于是用于密码管理的,那么在手机里操作会很频繁的被按下home键而切换到后台的,所以希望程序被按下home键的时候隐藏到后台就自动锁定程序,再激活APP的时候要求重新输入密码才可以操作。那么问题来了,在Firemonkey里面如何捕获按下home键的事件呢?网上搜索各种资料,终于找到了答案,这里分享出来具体的解决方法:
定义一个事件方法:
function TMaster.HandleAppEvent(AAppEvent: TApplicationEvent; AContext: TObject): Boolean; begin case AAppEvent of TApplicationEvent.FinishedLaunching: ; TApplicationEvent.BecameActive: ; TApplicationEvent.WillBecomeInactive: begin if not Assigned(LoginFrame) then ShowFrame(TLoginFrame, Master, False); LoginFrame.BringToFront; end; TApplicationEvent.EnteredBackground: ; TApplicationEvent.WillBecomeForeground: ; TApplicationEvent.WillTerminate: ; TApplicationEvent.LowMemory: ; TApplicationEvent.TimeChange: ; TApplicationEvent.OpenURL: ; end; Result := True; end;
使用IFMXApplicationEventService接口里的SetApplicationEventHandler方法将上述事件方法作为参数进行调用即可实现,HandleAppEvent方法里会触发各种程序相关的事件通知。代码如下:
var SvcEvents: IFMXApplicationEventService; begin if TPlatformServices.Current.SupportsPlatformService(IFMXApplicationEventService, IInterface(SvcEvents)) then begin SvcEvents.SetApplicationEventHandler(HandleAppEvent); end; end;
注:开发环境Delphi10.2