Home

An Interactive Service

The service in this example displays a simple GUI, and can run both as a standalone application and as a NT service.

It demonstrates how to subclass the QtService class, the use of run(), stop(), pause(), resume(), user() and isRunning(), and how to use parseArguments() to control the service.

    #include <qtservice.h>
    #include <qapplication.h>
    #include <qlabel.h>

    class InteractiveService : public QtService
    {
    public:
        InteractiveService();

    protected:
        int run( int argc, char **argv );
        void pause();
        void resume();
        void user(int code);

    private:
        QLabel *gui;
    };
The InteractiveService class reimplements the pure virtual function QtService::run() as well as the virtual functions QtService::pause(), QtService::resume() and QtService::user(). A single QLabel displays a simple user interface.

    InteractiveService::InteractiveService()
        : QtService( "Qt Interactive Service", "A Qt service with user interface." ), gui( 0 )
    {
    }
The constructor passes the service name and description to the QtService constructor, and initializes the data members.

    int InteractiveService::run( int argc, char **argv )
    {
        QApplication app( argc, argv );

        if ( !isRunning() ) {
            gui = new QLabel( "Running standalone!", 0, "gui" );
            app.setMainWidget( gui );
        } else {
            gui = new QLabel( "Running as a service!", 0, "gui", WStyle_Customize | WStyle_NoBorder | WStyle_StaysOnTop );
        }
The implementation of run() creates a QApplication object and passes the commandline parameter to the constructor.

Depending on whether the run() is called in the context of a standalone execution or a service the GUI is created with different contents.

        gui->move( app.desktop()->availableGeometry().topLeft() );
        gui->show();

        return app.exec();
    }
The user interface is moved to the topleft corner of the primary screen and displayed. Finally control is passed to the event loop.

    void InteractiveService::pause()
    {
        if ( gui )
            gui->hide();
    }

    void InteractiveService::resume()
    {
        if ( gui )
            gui->show();
    }
The implementation of pause() and resume() simply hide and show the user interface.

    void InteractiveService::user(int code)
    {
        gui->setText( "Command code " + QString::number(code) );
    }
The implementation of user() displays the requested command in the label.

    int main( int argc, char **argv )
    {
        InteractiveService service;
        return service.parseArguments( argc, argv );
    }
The main entry point function creates the service object and uses the parseArguments() function to handle the command line parameters passed to the application (see the QtService::parseArguments() documentation for details).
Copyright © 2003-2005 TrolltechTrademarks
Qt Solutions