What is the best way to autostart an action after OnShow event?

折月煮酒 提交于 2019-11-30 13:50:37

问题


I have a small application that most of the time have an action behind a Start-button that should be triggered from the commandline parameter /AUTORUN. If that parameter is missing the user could also press it manually.

My question is where should I place this check for commandline so when it is given the GUI is still updated. The current solution is this, but the GUI is not updated until the action is finished.

procedure TfrmMainForm.FormShow(Sender: TObject);
begin
  if FindCmdLineSwitch('AUTORUN') then
    btnStart.Click;
end;

回答1:


Post yourself a message from your OnShow event handler. This will be processed as soon as your application starts servicing its message queue. That only happens when the application is ready to receive input. Which matches your my understanding of your requirements.

const
  WM_STARTUP = WM_USER;
....
procedure TfrmMainForm.FormShow(Sender: TObject);
begin
  PostMessage(Handle, WM_STARTUP, 0, 0);
  OnShow := nil;//only ever post the message once
end;

Add a message handler to deal with the message:

procedure WMStartup(var Msg: TMessage); message WM_STARTUP;

You'd implement that like this:

procedure TfrmMainForm.WMStartup(var Msg: TMessage);
begin
  inherited;
  if FindCmdLineSwitch('AUTORUN') then
    btnStart.Click;
end;



回答2:


In the FormShow post yourself a message. In the message handler run your btnStart.

TfrmMainForm = class(TForm)
// snip
private
  procedure AutoStart(var Message: TMessage); message wm_user;
// snip
end

procedure TfrmMainForm.FormShow(Sender: TObject);
begin
  if FindCmdLineSwitch('AUTORUN') then
    PostMessage(Handle, wm_user, 0, 0);
end;

procedure TfrmMainForm.AutoStart(var Message: TMessage);
begin
  btnStart.Click;
end;



回答3:


An easy way would be a timer, with an event like this:

begin
  Timer1.Enabled := False;
  if FindCmdLineSwitch('AUTORUN') then
    btnStart.Click;
end;

And an interval of a few thousand milliseconds.



来源:https://stackoverflow.com/questions/14318807/what-is-the-best-way-to-autostart-an-action-after-onshow-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!