Mouse Input

As usual, the relevant C++ documentation is excellent. This little demonstration loads a font pre-installed in Windows and may not run in the debugger. Press Ctrl+F9 to compile then execute the program directly. You can see from the display the mouse coordinates and whether or not a mouse button is down.

For a more impressive (but more complicated) example of mouse handling, see our marionette.

The Code

program PasSFMLMouseDemo;
{$Apptype GUI}
uses
  SysUtils, SfmlGraphics, SfmlSystem, SfmlWindow;

const
  WINDOW_WIDTH = 300;
  WINDOW_HEIGHT = 200;
var
  Window: TSfmlRenderWindow;
  Event: TsfmlEvent;
  Text: TsfmlText;
  MouseDown: Boolean = False;
begin
  Window := TSfmlRenderWindow.Create(SfmlVideoMode(WINDOW_WIDTH, WINDOW_HEIGHT, 32),
                                     AnsiString('Mouse Demo'), [sfTitleBar, sfClose], nil);
  Window.SetVerticalSyncEnabled(True);
  Text := TsfmlText.Create;
  Text.Font := SfmlFontCreateFromFile('C:\Windows\Fonts\arial.ttf');

  while Window.isOpen do
    begin
      while SfmlRenderWindowPollEvent(Window.Handle, Event) do
        begin
          case Event.EventType of
            sfEvtClosed:      SfmlRenderWindowClose(Window.Handle);
            sfEvtKeyPressed:  if Event.Key.Code = sfKeyEscape then   // Escape key pressed
                                SfmlRenderWindowClose(Window.Handle);
            sfEvtMouseButtonPressed: MouseDown := True;
            sfEvtMouseButtonReleased: MouseDown := False;
          end;
        end;
      Window.Clear(SfmlWhite);
      Text.CharacterSize := 16;
      Text.Color := sfmlBlue;
      Text.Position := sfmlVector2f(10, 10);
      if MouseDown then
        Text.&String := 'Mouse button down'
      else
        Text.&String := 'Mouse buttons up';
      Window.Draw(Text);
      Text.Position := sfmlVector2f(10, 30);
      Text.&String := 'Mouse X: ' + IntToStr(Window.MousePosition.X) +
                      '   Mouse Y: ' + IntToStr(Window.MousePosition.Y);
      Window.Draw(Text);
      Window.Display;
    end;
end.
    
Programming - a skill for life!

How to use the Simple Fast Media Library in Lazarus