-11 Vote

Delphi/Lazarus: Set ModalResult without Button programmatically

Question by Guest | 2015-12-14 at 19:07

I am using a Form containing two buttons setting the ModalResult to mrOk or mrCancel. That is working perfectly. I am showing the form calling ShowModal and whenever the user clicks on one of the buttons, the window closes automatically and I can evaluate the result.

Now, I also want to allow the user to not only click on the button in order to close the window, but also to use a keyboard shortcut to do so. For this, I have set KeyPreview to true in the forms properties and I have defined the following procedure.

procedure TForm2.FormKeyDown(Sender: TObject; var Key: Word; 
   Shift: TShiftState);
begin

  if key = ord(#13) then begin
     ModalResult := mrOk;
     Close;
  end;

end; 

The invocation is done in the following way:

if Form2.ShowModal = mrOk then begin
   // Code after Okay
end else begin
   // Code after Cancel
end;

Unfortunately, this is not working at all. The ModalResult always remains mrNone although I have set it to mrOk. What am I doing wrong here?

ReplyPositiveNegative
0Best Answer2 Votes

The problem is calling Close. Instead, you should just omit Close. So, you can change your code to that:

if key = ord(#13) then begin
   ModalResult := mrOk;
end;

That worked in my tests. The form nevertheless closes automatically, you do not have to care about that in your code.
2015-12-14 at 20:04

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.