Cancelling the rest of a procedure if InputQuery i

2019-09-11 19:20发布

问题:

procedure TForm1.Button2Click(Sender: TObject);
var
  Button: TButton;
  Example : String;

begin

  if {Example = ''} InputQuery('Put a question/request here', Example) then
  Repeat                                                           

    InputQuery('Put a question/request here', Example);

if InputQuery = False then
 Abort
 else
  Until Example <> ''; //or InputBox.


  Button := TButton.Create(self);
  Button.Parent := self;
  //Button properties go here
  Button.Caption := (Example);
  //Any procedures can go here

end;

This procedure continues after the repeat loop even if the user presses cancel. I've tried using the GoTo function using the CancelCreateButton label if InputQuery = False but I just get errors(so i removed some of the code).

How can i make it so that if the user clicks cancel on the inputquery it cancels the procedure and doesn't create a button?

回答1:

If the Cancel button of the input query form is pressed, then the call to InputQuery returns False. In that scenario you should call Abort, the silent exception, to skip the rest of the event handler.

if not InputQuery(...) then
  Abort;

If you want to perform validation in a loop then that would look like this:

repeat
  if not InputQuery(..., Name) then
    Abort;
until NameIsValid(Name);


回答2:

You can also use the Exit function



回答3:

You have too many calls to InputQuery, three when you only need one; it is better to capture the result of InputQuery to a Boolean variable and use that for execution flow control. Try something like this instead:

procedure TForm1.Button2Click(Sender: TObject);
var
  FSeatButton: TButton;
  Name : String;
  InputOK : Boolean;
  Label
  CancelCreateButton;
begin
  InputOK := InputQuery('Enter Students Name', 'Name', Name);
    // You can add check's on the validity of the student's name 
    // (e.g, is it a duplicate) here and update the value of InputOK 
    // (to False) if you don't want the button creation to go ahead

  if InputOK then begin
    FSeatButton := TButton.Create(self);
    FSeatButton.Parent := self;
    FSeatButton.Left := 100;
    FSeatButton.Top := 100;
    FSeatButton.Width := 59;
    FSeatButton.Height := 25;
    FSeatButton.Caption := (Name);
    FSeatButton.OnMouseDown := ButtonMouseDown;
    FSeatButton.OnMouseMove := ButtonMouseMove;
    FSeatButton.OnMouseUp := ButtonMouseUp;
  end;
end;

Assuming that does what you intend for a single student, you can reinstate the repeat ... until to get the behaviour you need.



标签: delphi input