I needed to create a application where the Timage can be hide after a certain key is pressed under a certain situation.
I have set KeyPreview to true, and the image can hide within the onKeyPress method, everything worked properly. But as soon as I implemented a while loop inside the onKeyPress method, the image doesn't hide anymore after the appropraite key is being pressed.
What should I do to fix that?
You shouldn't do a WHILE loop inside an event handler. The event handlers should do a simple update to UI and then exit, to allow Delphi to reflect the UI update on screen.
Move your WHILE loop out of the KeyPress event, preferably into a background thread, alternately into the Application.OnIdle event (where you then perform ONE iteration of the WHILE loop within the OnIdle event and turn off processing when the WHILE condition isn't valid anymore).
The "poor man"'s solution (and not one that is recommended, but can be used if all other options are too complicated) is to call
either within the WHILE loop (if you are altering UI elements in the loop) or just before starting the WHILE loop (if you're not).
Note, however, that while the "Application.Processmessages" code is running, all other event handlers are capable of being run, so if you, f.ex., run an Application.ProcessMessages within a Timer Event, the Timer Event may be called again before the currently running Timer Event has finished running (leading to an infinite recursive loop and eventually a stack overflow and termination of your program).