11.2. Single-Instance ApplicationsSometimes it only makes sense to run one instance of an application. Examples include Kicker, the KDE panel, Kwin the KDE window manager, and KPPP, the Internet dial-up tool. To allow developers to create single-instance applications with minimal effort, KDE offers KUniqueApplication. It is a subclass of KApplication and thus offers all of KApplication's functionality and ensures that only one instance of the application is running. To use KUniqueApplication, you need to modify your usual main() function a bit; see Listing 11.4. Example 11.4. main.cpp: A main() Function Suitable for Starting a Single-Instance Application
KUniqueapplication accomplishes the feat of starting only one application using DCOP, an interprocess communication system (see Chapter 13, "DCOP—Desktop Communication Protocol" for a discussion). When KUnique::start() is called, KUniqueApplication tries to register itself with DCOP under your application's name (kunique in this case). If that name is already in use, KUnique::start() returns false and your application exits. Otherwise, your application is registered under its name. In either case, a DCOP call is sent off, which calls the virtual method KUnique::newInstance() (see Listing 11.5). Example 11.5. kunique.cpp: Class Definition for KUnique, a Single-Instance Application
In the method newInstance() (lines 13-26), you either create a new instance of the main application widget (usually a subclass of KTMainWindow; here KSimpleApp is used—a main widget presented in Chapter 2) or, if it already exists, respond to the user's attempt to restart the application. Your application's response to a restart attempt might be the following:
In any case, the response should indicate to the user that you are aware of the user's attempt to start the application. At a minimum, you should set the currently running window as the active window using the static method KWin::setActiveWindow(). This method is demonstrated on line 24. KUnique interprets a request to start the application again as a request to perform the only action it knows: to reposition the text (see Chapter 2 for an explanation of this action). The final bit of code needed to compile KUnique, the header file, is given in Listing 11.6. Example 11.6. kunique.h: Class Declaration for KUnique
|