Which is the best place to initialize code? [duplicate] - delphi

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Splash Screen Programatically
Show a splash screen while a database connection (that might take a long time) runs
Which is the best place to initialize code such as loading INI file? I want first to show the form on screen so the user know that the app is loading and ONLY after that I want to call lengthy functions such as LoadIniFile or IsConnectedToInternet (the last one is REALLY slow).
The OnCreate is not good because the form is not yet ready and it will not show up on screen.
I do this I DPR but not working always:
program Test;
begin
Application.Initialize;
Application.Title := 'Test app';
Application.CreateForm(TfrmTest, frmTest);
frmTest.Show; <---------------------- won't show
LateInitialize;
Application.Run;
end.
The form will not show until LateInitialize (4-5 seconds) is executed.
procedure LateInitialize;
begin
CursorBussy;
TRY
// all this won't work also. the form won't show
frmTest.Visible:= TRUE;
Application.ProcessMessages;
frmTest.Show;
Application.ProcessMessages;
frmTest.BringToFront;
frmTest.Update;
Application.ProcessMessages;
DoSomethingLengthy; {4-5 seconds}
FINALLY
CursorNotBussy;
END;
end; <--------- Now the form shows.
And yes, frmTest it is my only form (the main form).

After calling frmTest.Show, you can call frmTest.Update to let it render onscreen, before then calling LateInitialize. But until Application.Run is called, the main message loop will not be running, so the form will not be able to do anything else until then.
Another option is to use the form's OnShow event to post a custom window message back to the form via PostMessage(), then have the form call LateInitialize when it receives that message at a later time. That will allow the form to process painting messages normally until LateInitialize is called.
Anything that blocks the main thread for more than a few milliseconds/seconds really should be moved into a separate worker thread instead (especially things like IsConnectedToInternet). The main thread should be used for running the UI.

An easy way to do this, is to send a message to yourself.
I do this all the time
const
MSG_AFTERCREATE = WM_APP + 4711;
...
procedure OnCreate(Sender: TObject);
procedure AfterCreate(var message: TMessage); message MSG_AFTERCREATE;
...
Implementation
procedure OnCreate(Sender: TObject);
begin
PostMessage(Self.Handle, MSG_AFTERCREATE, 0, 0);
end;
procedure AfterCreate(var message: TMessage);
begin
//Do initializing here... the form is done creating, and are actually visible now...
end;

Variant 1: Use TTimer with a 1 second delay, run it from main form's OnShow
In TTimer do the initialisation
This will give time for most components to initialize and draw themselves
Variant 1.1: use message method in function and call Win API PostMessage (but not SendMessage aka Perform) from OnShow. This is seemilar but more cheap and fast. However that message "do init now" sometimes may be received before some complex component on the form would fully draw itself.
Variant 2: use threads (OmniThreadsLib or even plain TThread)
Launch it from MainForm OnCreate and let it prepare all data in background, then enable all needed buttons, menus, etc
That is truly the best way if you have long and blocking functions, liek you described IsConnectedToInternet.
Variant 3: use SplashScreen before showing main form.
That is good because users see that application not read yet.
That is bad for that very reason - people start feeling your program is slow. Google Chrome was told to draw their main form as picture in 1st moments just to make look "we are already started" even the actual control would be ready a bit later.

A long time ago in another forum far far away, someone posted the following to document the life cycle of a form. I have found it useful, so am sharing it here.
Create OnCreate
Show OnShow
Paint OnPaint
Activate OnActivate
ReSize OnResize
Paint OnPaint
Close query OnCloseQuery
Close OnClose
Deactivate OnDeactivate
Hide OnHide
Destroy OnDestroy
Try the OnActivate event.

Related

TDialogService.ShowMessage not blocking on Win10

In my Delphi 10.4 FMX program, I am asking the user for a new file name using the code below
procedure TForm6.btnBlockingClick(Sender: TObject);
begin
//In Win10, this blocks form access when ShowMessage is called
NameCallBack(mrOk, ['name']);
end;
procedure TForm6.btnNonBlockingClick(Sender: TObject);
begin
//In Win10, this does not block form access when ShowMessage is called in the NameCallBack routine.
TDialogService.InputQuery('Enter name', ['Name'], [''], NameCallBack);
end;
procedure TForm6.NameCallBack(const AResult: TModalResult; const AValues: array of string);
begin
if aResult = mrOK then
TDialogService.ShowMessage('Ok pressed')
else
TDialogService.ShowMessage('Cancel pressed');
end;
Any idea why ShowMessage is not blocking when NameCallBack is used as the Callback event for InputQuery? In Win10, what is the best way to show a message to a user in this type of callback routine that keeps the user from accessing the underlying form until the dialog is closed in some way.
FYI: the same thing happens if you use MessageDialog, to allow user interaction, instead of ShowMessage in the callback routine.
Note: this logic works in OSX and IOS, with both dialogs blocking. On Android, neither dialog is blocking but is not a problem, as touching anywhere but the dialogs closes the dialog and requires a second touch to interact with the underlying form again. On Win10, I can doing anything I want with the underlying form while the ShowMessage dialog is visible when used in a callback event.
Thanks for any help with this.
This may not be the best way to work around the bug I found, but here is what I did in case someone else has this problem.
I added a timer to my form, set the interval to 200 and disabled it.
For any TDialogServices.MessageDialog and TDialogServices.InputQuery callback routine where the callback routine also called MessageDialog or ShowMessage, I moved the callback logic into new routines. I then changed the callback routines to set a form variable to indicate which callback routine was called, saved off the relevant info from the callback routine as needed, then enabled the timer.
In the timer event, I first disable the timer then call the new routines based on the form variable.
This now allows both the original dialog and the dialog needed in the callback routine to be blocking on Win10. In addition, Android, OSX and IOS appear to still work correctly as explained in my question.

OnShown event for TForm?

At program start, in the OnActivate event handler, I need to do something which blocks the program for a few seconds. During this time the form's client area is still not completely painted, which looks ugly for the user. (During this blocked time I don't need the program to respond to clicks or other user actions, so there is no need to put the blocking operation into a thread - I just need the form to be completely painted). So I use TForm.Update and Application-ProcessMessages to update the form before the blocking operation which works very well:
procedure TForm1.FormActivate(Sender: TObject);
begin
Form1.Update;
Application.ProcessMessages;
Sleep(7000);
end;
However, I wonder whether there is not another more elegant solution for this problem. This could be for example a OnShown event implemented in a descendant of TForm which will be fired AFTER the form has been completely painted. How could such an event be implemented?
Your real problem is that you are blocking the UI thread. Simply put, you must never do that. Move the long running task onto a different thread and thus allow the UI to remain responsive.
If you are looking for event which is fired when application finishes loading/repainting you should use TApplication.OnIdle event
http://docwiki.embarcadero.com/Libraries/XE3/en/Vcl.Forms.TApplication.OnIdle
This event is fired once application is read to recieve users input. NOTE this event will be fired every time application becomes idle so you need to implement some controll variable which will tel you when OnIdle even was fired for the first time.
But as David already pointed out it is not good to block your UI (main thread). Why? When you block your main thread the application can't normally process its messages. This could lead to OS recognizing your application as being "Hanged". And aou definitly wanna avoid this becouse it could cause the users to go and forcefully kill your application whihc would probably lead to data loss. Also if you ever wanna design your application for any other platforms than Windows your application might fail the certification proces becouse of that.
In the past a simple PostMessage did the trick.
Essentially you fire it during DoShow of the base form:
procedure TBaseForm.DoShow;
begin
inherited;
PostMessage(Handle, APP_AFTERSHOW, 0, 0);
end;
then catch the msg and create an AfterShow event for all forms inherited from this base form.
But that no longer works, well not if you are skinning and have a good number of VCL controls.
My next trick was to spawn a simple thread in DoShow and check for IsWindowVisible(Handle) and IsWindowEnabled(Handle). That really sped things up it cut 250ms from load time since db opening and other stuff was already in the AfterShow event.
Then finally I thought of madHooks, easy enough to hook the API ShowWindow for my application and fire APP_AFTERSHOW from that.
function ShowWindowCB(hWnd: HWND; nCmdShow: Integer): BOOL; stdcall;
begin
Result := ShowWindowNext(hWnd, nCmdShow);
PostMessage(hWnd, APP_AFTERSHOW, 0, 0);
end;
procedure TBaseForm.Loaded;
begin
inherited;
if not Assigned(Application.MainForm) then // Must be Mainform it gets assigned after creation completes
HookAPI(user32, 'ShowWindow', #ShowWindowCB, #ShowWindowNext);
end;
To get the whole thing to completely paint before AfterShow it still needed a ProcessPaintMessages call
procedure TBaseForm.APPAFTERSHOW(var AMessage: TMessage);
begin
ProcessPaintMessages;
AfterShow;
end;
procedure ProcessPaintMessages; // << not tested, pulled out of code
var
msg: TMsg;
begin
while PeekMessage(msg, 0, WM_PAINT, WM_PAINT, PM_REMOVE) do
DispatchMessage(msg);
end;
My final test was to add a Sleep to the AfterShow event and see the Form fully painted with empty db containers since the AfterShow events had not yet completed.
procedure TMainForm.AfterShow;
begin
inherited;
Sleep(8*1000);
......

Can't hide a window that's not been fully initialized

I have this awkward situation that causes an exception. I've found the problem but the solution is so far tricky to implement for me.
In our application, if a user stays in-active for a certain period of time, the security time-out procedure kicks in to prompt the user the password entry box.
However, whenever a form has a message box displayed during the FormShow() event for any particular reason (thing to pay attention here; the formShow event execution hasn't been fully completed yet) and the user decided to not click the OK button of the dialog box for a certain time, the security code kicks in and tries to hide all forms so that it can prompt a password.
This scenario will trigger the exception "Cannot change Visible in OnShow or OnHide".
Security code loops all forms using TScreen.FormCount and hides them using TForm(TScreen.Forms[ii]).Hide individually. Hide procedure will cause the exception, because I think this form has not completed it's loading procedure fully yet.
I've done tests, and if I display a message box after the FormShow() event is executed, the security code works perfectly fine and hides all windows without any issues.
I've tried several properties and window message checking to do an "if check" before hiding forms, like Screen.Forms[ii].Visible, Screen.Forms[ii].Active but no luck so far. The mentioned form will be visible and there's no guarantee that it will be active, and if it's active how am I going to hide other non active forms. So my question is, which property or Windows message would indicate that a form is fully loaded, or at least it has past the FormShow event of any given form that exists in TScreen.Forms?
I need an answer to what I am asking please, I need a generalized solution that needs to be implemented in the security code, I can't go through over a thousand forms we have in this giant application and individually try to find solutions to any validation/warning logic exist in those forms.
Thank you
The simple answer is to stop showing the modal dialog in the OnShow of the owner form. Wait until the form has finished showing before you display the modal dialog. If you make that change, and that change alone, your existing code will start to work.
The question title you chose was:
Can't hide a window that's not been fully initialized
And so the obvious solution is to wait until the window has been fully initialized.
The simplest way to achieve this is to move your code that currently runs in OnShow into a handler for CM_SHOWINGCHANGED:
procedure CMShowingChanged(var Message: TMessage); message CM_SHOWINGCHANGED;
Implement it like this:
procedure TMyForm.CMShowingChanged(var Message: TMessage);
begin
inherited; // this is what invokes OnShow
if Visible then
begin
// do what you previously did in OnShow
end;
end;
David Heffernan's solution gave me an idea and I solved this issue on my end.
I created following;
const
WM_SHOW_MESSAGE = WM_USER + 1;
private
procedure WMShowMessage(var Msg: TMessage); message WM_SHOW_MESSAGE;
Inside constructor;
PostMessage(Handle, WM_SHOW_MESSAGE, 0, 0);
And this will have the message box logic:
procedure MyMethod.WMShowMessage(var msg: TMessage); message WM_SHOW_MESSAGE;

Delphi GUI Testing and Modal Forms

In this interesting blog post on delphiXtreme I read about DUnit's built-in GUI testing capabilities (basically an alternative test case class TGUITestCase defined in unit GUITesting that has several utility functions for invoking actions in the GUI). I was quite happy with it until I noticed that it didn't work with modal forms. For example the following sequence won't work if the first button shows a modal configuration form:
Click ('OpenConfigButton');
Click ('OkButton');
The second Click is only executed when the modal form is closed, which I have to do manually.
I don't know much about how modal forms work in the background but there must be some way to circumvent this behaviour. Naively, I want to somehow execute the ShowModal "in a thread" so that the "main thread" stay responsive. Now I know that running ShowModal in a thread will probably mess up everything. Are there any alternatives? any way to circumvent the blocking nature of a ShowModal? Has anybody some experiences with GUI testing in Delphi?
I know about external tools (from QA or others) and we use those tools, but this question is about GUI testing within the IDE.
Thanks!
You can't test modal forms by calling ShowModal; because as you have quite rightly discovered, that results in your test case code 'pausing' while the modal form awaits user interaction.
The reason for this is that ShowModal switches you into a "secondary message loop" that does not exit until the form closes.
However, modal forms can still be tested.
Show the usually Modal form using the normal Show method.
This allows your test case code to continue, and simulate user actions.
These actions and effects can be tested as normal.
You will want an additional test quite particular to Modal forms:
A modal form is usually closed by setting the modal result.
The fact that you used Show means the form won't be closed by setting the modal result.
Which is fine, because if you now simulate clicking the "Ok" button...
You can simply check that the ModalResult is correct.
WARNING
You can use this technique to test a specific modal form by explicitly showing it non-modally. However, any code under test that shows a modal form (e.g. Error Dialog) will pause your test case.
Even your sample code: Click ('OpenConfigButton'); results in ShowModal being called, and cannot be tested in that manner.
To resolve this, you need your "show commands" to be injectible into your application. If you're unfamliar with dependency injection, I recommend Misko Hevery's Clean Code Talks videos available on You Tube. Then while testing, you inject a suitable version of your "show commands" that won't show a modal form.
For example, your modal form may show an error dialog if validation fails when the Ok button is clicked.
So:
1) Define an interface (or abstract base class) to display an error messages.
IErrorMessage = interface
procedure ShowError(AMsg: String);
end;
2) The form you're testing can hold an injected reference to the interface (FErrorMessage: IErrorMessage), and use it to show an error whenever validation fails.
procedure TForm1.OnOkClick;
begin
if (Edit1.Text = '') then
FErrorMessage.ShowError('Please fill in your name');
else
ModalResult := mrOk; //which would close the form if shown modally
end;
3) The default version of IErrorMessage used / injected for production code will simply display the message as usual.
4) Test code will inject a mock version of IErrorMessage to prevent your tests from being paused.
5) Your tests can now execute cases that would ordinarily display an error message.
procedure TTestClass.TestValidationOfBlankEdit;
begin
Form1.Show; //non-modally
//Do not set a value for Edit1.Text;
Click('OkButton');
CheckEquals(0, Form1.ModalResult); //Note the form should NOT close if validation fails
end;
6) You can take the mock IErrorMessage a step further to actually verify the message text.
TMockErrorMessage = class(TInterfaceObject, IErrorMessage)
private
FLastErrorMsg: String;
protected
procedure ShowError(AMsg: String); //Implementaion trivial
public
property LastErrorMsg: String read FLastErrorMsg;
end;
TTestClass = class(TGUITesting)
private
//NOTE!
//On the test class you keep a reference to the object type - NOT the interface type
//This is so you can access the LastErrorMsg property
FMockErrorMessage: TMockErrorMessage;
...
end;
procedure TTestClass.SetUp;
begin
FMockErrorMessage := TMockErrorMessage.Create;
//You need to ensure that reference counting doesn't result in the
//object being destroyed before you're done using it from the
//object reference you're holding.
//There are a few techniques: My preference is to explicitly _AddRef
//immediately after construction, and _Release when I would
//otherwise have destroyed the object.
end;
7) Now the earlier test becomes:
procedure TTestClass.TestValidationOfBlankEdit;
begin
Form1.Show; //non-modally
//Do not set a value for Edit1.Text;
Click('OkButton');
CheckEquals(0, Form1.ModalResult); //Note the form should NOT close if validation fails
CheckEqulsString('Please fill in your name', FMockErrorMessage.LastErrorMsg);
end;
There is actually a way to test modal windows in Delphi. When a modal window is shown your application still processes windows messages so you could post a message to some helper window just before showing the modal window. Then your message would be handled from the modal loop allowing you to execute code while the modal window is still visible.
Recently I've been working on a simple library to handle this very problem. You can download the code from here: https://github.com/tomazy/DelphiUtils (see: FutureWindows.pas).
Sample usage:
uses
Forms,
FutureWindows;
procedure TFutureWindowsTestCase.TestSample;
begin
TFutureWindows.Expect(TForm.ClassName)
.ExecProc(
procedure (const AWindow: IWindow)
var
myForm: TForm;
begin
myForm := AWindow.AsControl as TForm;
CheckEquals('', myForm.Caption);
myForm.Caption := 'test caption';
myForm.Close();
end
);
with TForm.Create(Application) do
try
Caption := '';
ShowModal();
CheckEquals('test caption', Caption);
finally
Free;
end;
end;

'working, please wait' screen with thread?

Perhaps, it is very easy for you, but I am hard working on a project (for educational purposes) that is querying adsi with TADSISearch component, for several days. I'm trying to show a 'Working, Please wait..' splash screen with a man worker animated gif on Form2 while TADSISearch is searching the Active Directory. Although i tried every possibilities according to me, but i couldn't succeed. I tried to use TADSISearch in a thread, but thread is terminating before ADSIsearch finishes. I think TADSISearch is not thread safe. What do you think? Also, another way that I created Form2 and used a thread for updating it but the animated gif is stopping while main form gone adsi searching. What can you say about these? How can i make a please wait screen while ADSISearch is working and keep main form responding. Application.ProcessMessages or timer is not a way too. Thanks a lot for reading and answers.
The graphical user interface should be updated by the main thread. You should put your search code into a separate thread, and while the searcher thread is working, your main thread can show the animation along with "Please wait" message.
Your searcher thread can notify the main thread when search is done by any of the available synchronization techniques. The simplest one is to define a method in your thread class which stops the animation in user interface, and pass that method to Synchronize at the end of Execute method of your searcher thread.
Your searcher thread code will be something like this:
type
TMyThread = class(TThread)
private
procedure NotifyEndOfThread;
protected
procedure Execute; override;
end;
implementation
uses MainFormUnit;
procedure TMyThread.NotifyEndOfThread;
begin
MainForm.ShowAnimation := False;
end;
procedure TMyThread.Execute;
begin
try
{Add your search code here}
finally
Synchronize(NotifyEndOfThread);
end;
end;
And your main thread's code will be like this:
TMainForm = class(TForm)
...
private
FShowAnimation : Boolean;
procedure SetShowAnimation(Value: Boolean);
public
property ShowAnimation : Boolean read FShowAnimation write SetShowAnimation;
end;
procedure TMainForm.SetShowAnimation(Value: Boolean);
begin
FShowAnimation := Value;
if FShowAnimation then
{Add animation code here}
else
{Stop animation}
end;
Maybe you can try this:
Threaded Splashscreen for Delphi
http://cc.embarcadero.com/Item/20139
I use this on a touchscreen/terminal application (thin client, Wifi, RemObjects, etc) and it works nice!
Also got an animated gif working.
How can the thread terminate before the search is finished? If the search is executed in the thread and you have only one instance of the thread it should work.
Can you not just do a
f := TMyWaitForm.Create(self);
try
f.Show();
...start the TADSISearch...
finally
FreeAndNil(f);
end;
Putting an animated GIF on the TMyWaitForm (which displays itself) ?
I have a progress form when building websites in my web creation program, and this works like a charm.
You even may consider showing some state information on the wait form (if the TADSISearch component/software has a call back function or event which can be assigned).
Displaying a running clock showing the amount of time the process is taking, is also a nice touch.

Resources