Mega Code Archive

 
Categories / Delphi / Examples
 

How to pause an app while waiting for a button click

Title: How to pause an app while waiting for a button click Question: I want to force my user to click one of two buttons before my application can continue but I don''t want to use a modal form to make this happen. Answer: This particular problem came about because of a letter merge printing feature in the app I was working on. When the user selected the menu option to print letters from within a specific module of the program, I presented a panel which gave the user some options for recording letter history and printing labels in addition to printing the letters themselves. Here is how I solved the problem: I set the buttons (btnContinue and btnCancel) on a panel that is disabled and in back of the regular items on my screen. I also set up two boolean variables - lContinue and lCancel. When the user selected the menu option to print letters, I run the following code: procedure MyForm.PrintLettersClick(Sender:TObject); begin pnlMain.enabled := False; //disable all other parts of the screen lContinue := False; lCancel := False; pnlLtr.BringToFront; pnlLtr.Enabled := True; while not lContinue and not lCancel do application.processmessages; //this loop pauses waiting for click pnlLtr.Enabled := False; pnlLtr.SendToBack; If lContinue then begin //process the letters end pnlMain.Enabled := False; //reenable the rest of the screen end; These are the OnClick event handlers for the buttons: procedure MyForm.btnContinueClick(Sender: TObject); begin lContinue := True; end; procedure MyForm.btnCancelClick(Sender: TObject); begin lCancel := True; end; So, when the user clicks on one of the buttons, either lContinue or lCancel is set to True and the while loop is cancelled, allowing the program to continue processing. The important piece here is the "application.processmessages" - without this statement, the button click event would never get handled and the while loop would just continue forever or until the user shut down the program from the task manager.