3
Sep
0
C++ – Windows API – Windows Focus (with Qt)
A simple class to know when a window gets or losses focus on windows with Qt.
Edit : I finally use another system (the isActive function) but this post can be useful anyway to work with windows API.
Header (with many in lining functions)
#ifndef LOSTFOCUSHANDLER_H
#define LOSTFOCUSHANDLER_H
#include <QObject>
#include <QTimer>
#include <windows.h>
class LostFocusHandler : public QObject
{
Q_OBJECT
public:
LostFocusHandler(QObject *parent = 0);
~LostFocusHandler();
void setTarget(HWND itarget){
target = itarget;
}
bool hasCurrentFocus(){
return GetActiveWindow() == target;
}
void start(){
hasFocus = (GetActiveWindow() == target);
timer.start();
}
void stop(){
timer.stop();
}
static bool hasCurrentFocus(HWND itarget){
return GetActiveWindow() == itarget;
}
signals:
void LostFocus();
void GetFocus();
protected slots:
void refresh();
private:
QTimer timer;
bool hasFocus;
HWND target;
};
#endif // LOSTFOCUSHANDLER_H
Implementation
#include "LostFocusHandler.h"
LostFocusHandler::LostFocusHandler(QObject *parent)
: QObject(parent)
{
target = 0;
timer.setInterval( 250 );
connect(&timer,SIGNAL(timeout()),this,SLOT(refresh()));
}
LostFocusHandler::~LostFocusHandler()
{
timer.stop();
}
void LostFocusHandler::refresh(){
if(hasFocus && GetActiveWindow() != target){
hasFocus = false;
emit LostFocus();
}
else if(!hasFocus && GetActiveWindow() == target){
hasFocus = true;
emit GetFocus();
}
}
Utilization
//in a QWidget
protected slots:
void run(){
setWindowTitle("Run");
}
void end(){
setWindowTitle("Stop");
}
...
void MyProg::create(){
focusManager.setTarget(winId());
connect(&focusManager,SIGNAL(LostFocus()),this,SLOT(run()));
connect(&focusManager,SIGNAL(GetFocus()),this,SLOT(end()));
focusManager.start();
}
Enjoyed reading this post?
Subscribe to the RSS feed and have all new posts delivered straight to you.
Subscribe to the RSS feed and have all new posts delivered straight to you.
