Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Close Event from nothing  (Read 1623 times)

0 Members and 1 Guest are viewing this topic.

iSkull

  • Newbie
  • *
  • Posts: 6
    • View Profile
Close Event from nothing
« on: March 20, 2011, 09:38:01 am »
Hello,

I am encountering a problem with sf::Event::Closed

Let's say i have this code:

Code: [Select]
#include <SFML/Graphics.hpp>
int main()
{
    sf::RenderWindow App(sf::VideoMode(600,300,32), "Test");
    sf::Event Event;

    sf::Image img(10,10,sf::Color(0,0,0));
    sf::Sprite Spr;

    bool running=true;

    App.UseVerticalSync(true);

    img.SetSmooth(false);

    Spr.SetImage(img);
    Spr.SetScale(2,2);
    Spr.SetPosition(300,280);

    while(running)
    {
        App.GetEvent(Event);
       
        if(Event.Type==sf::Event::Closed)
                running=false;

        if(Event.Type==sf::Event::KeyPressed) {if(Event.Key.Code==sf::Key::Escape)running=false;}

        if(App.GetInput().IsKeyDown(sf::Key::Left))Spr.Move(-10,0);
        if(App.GetInput().IsKeyDown(sf::Key::Right))Spr.Move(10,0);
        if(Spr.GetPosition().x<-5) Spr.SetX(600); else if(Spr.GetPosition().x>605) Spr.SetX(0);

        App.Clear(sf::Color(0,150,0));
        App.Draw(Spr);
        App.Display();
    }
}


A simple program showing a moving square.

When I run it, 70% of times will instantly exit it.
In the console mode it returns 0, so i think there aren't errors or problem with the code.

I removed
Code: [Select]
if(Event.Type==sf::Event::Closed)
                running=false;


And it worked perfectly, so it seems that the program gets a Closed event from nothing.
Is there a way to fix this or an alternative to sf::Event::Closed?

Laurent

  • Administrator
  • Hero Member
  • *****
  • Posts: 32498
    • View Profile
    • SFML's website
    • Email
Close Event from nothing
« Reply #1 on: March 20, 2011, 10:01:06 am »
Read the tutorials and examples, this is not how events are supposed to be handled.

You must process the event only if GetEvent returned true; otherwise the event variable may contain anything.

Code: [Select]
while (App.GetEvent(Event))
{
    if(Event.Type==sf::Event::Closed)
            running=false;

    if (Event.Type==sf::Event::KeyPressed) {if(Event.Key.Code==sf::Key::Escape)running=false;}
}
Laurent Gomila - SFML developer

iSkull

  • Newbie
  • *
  • Posts: 6
    • View Profile
Close Event from nothing
« Reply #2 on: March 20, 2011, 10:05:24 am »
I get it now, thanks