Hi everyone,
I recently changed my Graphics-Class to a Singleton with a thread. Since that moment window->pollEvents(event) does not send any events. But I can still draw in the window.
I code with Windows 7, Code::Blocks, MinGW, SFML2, Boost 1.48
I created a minimal example, that has exactly this behavior. This code may look a bit crappy, but I removed the irrelevant parts.
First, I haven't had the "window->setActive(true/false);", but I got an error message: "Failed to active the window's context".
main.cpp
#include <SFML/Window.hpp>
#include "Graphics.h"
int main()
{
sGraphics->start();
sGraphics->join();
return 0;
}
Graphics.h
#ifndef GRAPHICS_H_
#define GRAPHICS_H_
#include <boost/thread.hpp>
#include <sfml/Window.hpp>
#include <sfml/Graphics/RenderWindow.hpp>
using namespace sf;
class Events;
class GraphicsState;
class Graphics {
boost::thread thread;
bool stillRunning;
RenderWindow *window;
int width, height;
static Graphics* instance;
Graphics();
public:
static Graphics* getInstance();
virtual ~Graphics();
void run();
void start();
void join();
void deinit();
bool isStillRunning();
void quit();
};
#define sGraphics Graphics::getInstance()
#endif /* GRAPHICS_H_ */
Graphics.cpp
#include <cstdio>
#include <SFML/Window.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Graphics/Text.hpp>
#include <exception>
#include "Graphics.h"
using namespace sf;
using namespace std;
Graphics::Graphics() {
char title[50] = "";
width = 800;
height = 600;
sprintf(title, "%s V%d.%d", "A Geek's Warfare", 0, 0);
VideoMode videoMode(width, height, 32);
unsigned int params = Style::Close | Style::Titlebar;
if(false)
params = Style::Fullscreen;
window = new RenderWindow(videoMode, title, params);
window->setActive(false);
stillRunning = true;
}
Graphics* Graphics::instance = NULL;
Graphics* Graphics::getInstance() {
if(!instance)
instance = new Graphics();
return instance;
}
Graphics::~Graphics() { }
void Graphics::run() {
try {
window->setActive(true);
while(isStillRunning()) {
Event event;
window->clear();
while(window->pollEvent(event))
if(event.type == sf::Event::Closed) {
quit();
}else if(event.type == sf::Event::KeyPressed) {
if(event.key.code == sf::Keyboard::Escape)
quit();
}
sf::Text text("Hello World!");
text.setCharacterSize(30);
text.setStyle(sf::Text::Bold);
text.setColor(sf::Color::Red);
text.setPosition(width / 2 - text.getGlobalBounds().width / 2, height / 2 - text.getGlobalBounds().height / 2);
window->draw(text);
window->display();
boost::this_thread::sleep(boost::posix_time::milliseconds(50));
}
} catch(exception& e) {
} catch(...) {
}
deinit();
}
void Graphics::start() {
thread = boost::thread(&Graphics::run, this);
}
void Graphics::join() {
thread.join();
}
void Graphics::deinit() {
window->close();
}
bool Graphics::isStillRunning() {
return stillRunning;
}
void Graphics::quit() {
stillRunning = false;
}