Recent

Author Topic: Problem with attach a key to a button  (Read 1480 times)

Tomi

  • Full Member
  • ***
  • Posts: 125
Problem with attach a key to a button
« on: July 01, 2023, 05:14:23 pm »
Hello!

I have a problem with a runtime created button in my program which can be controllable by keys. When the user press ESC the program halts, with any other keys the program changes its status:
if the actual screen is the title screen (2) then jump to first level (3). I create this exit button at key down on the title screen and change to the other screen. So far - everything is OK.
But when I click on this exit button and select NO (=cancel) instead of YES (=exit) and after this I try to activate this button with ESC key - nothing happening.
Therefore I complement piece of code of exit button create with this line: exitbutton.OnKeyDown:=@FormKeyDown;
But after this I get an error message, as you can see on the attached image. Maybe @FormKeyDown cannot be in FormKeyDown event?
I tried to replace piece of code of exit button create into FormCreate event and make this button invisible and disabled, then just enable these two properties in FormKeyDown in the previous place, but the situation is the same.
The first solution would be the best for me, that is creating this button at FormKeyDown event.
But what should I do to prevent that error and allow using ESC key with that button?

Code: Pascal  [Select][+][-]
  1. procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState
  2.   );
  3. begin
  4.   if Key=VK_ESCAPE then
  5.      exitbuttonclick(form1)
  6.   else
  7.   begin
  8.     case gamestatus of
  9.     2: begin
  10.             exitbutton:=TButton.Create(form1);
  11.             exitbutton.Parent:=form1;
  12.             exitbutton.Top:=2;
  13.             exitbutton.Left:=2;
  14.             exitbutton.Caption:='Esc';
  15.             exitbutton.OnKeyDown:=@FormKeyDown;
  16.             exitbutton.OnClick:=@exitbuttonclick;
  17.         (...)
  18.         gamestate=3;
  19.         end;

And the exitbuttonclick procedure:

Code: Pascal  [Select][+][-]
  1. procedure TForm1.exitbuttonclick(Sender: TObject);
  2. var answer,stilus: integer;
  3. begin
  4.  stilus:=MB_ICONQUESTION + MB_YESNO;
  5.  answer:=Application.MessageBox('Are you sure you want to exit?', 'Confirmation', stilus);
  6.  if answer=IDYES then
  7.     if gamestatus=3 then
  8.     begin
  9.          clearallobjects();
  10.          gamestatus:=0;
  11.          FreeAndNil(exitbutton);
  12.     end
  13.     else Close;
  14. end;
« Last Edit: July 01, 2023, 05:17:47 pm by Tomi »

 

TinyPortal © 2005-2018