3

I wonder how to create an application that would be capable to have only one instance of it running on a host OS at a time.. so to say a singleton app. I wonder how to create such singleton C++ app in Qt?

staackuser2
  • 12,172
  • 4
  • 42
  • 40
myWallJSON
  • 9,110
  • 22
  • 78
  • 149

3 Answers3

4

You could use the QtSingleApplication class from Qt Solutions. Notice that this is not a standard Qt class. You should download it. The QtSingleApplication component provides support for applications

that can be only started once per user.

AAEM
  • 1,837
  • 2
  • 18
  • 26
pnezis
  • 12,023
  • 2
  • 38
  • 38
2

When the application starts, create a file. When the application ends, remove the file.

If the file exists, exit with an error message.

BЈовић
  • 62,405
  • 41
  • 173
  • 273
  • thats the problem - user can rename app, and move it around...( – myWallJSON May 16 '12 at 07:12
  • This is a platform independent approach. If the application creates a file in a directory where it is stored, then this approach will work. The user can not move the application files while it is running. – BЈовић May 16 '12 at 07:14
  • He could just copy the app to another directory, and this new version will run fine, it will create a new file in the new location. (There are some workaround though, but troublesome.) – Cray May 16 '12 at 07:18
  • @VJovic He could copy it, although it might be that this is then conceptually another application. But you could also use Qt's `QSettings` interface for application directory independent storage (be it config files in the home directory or registry keys, depending on the OS). – Christian Rau May 16 '12 at 07:18
-1

You don't really need Qt for this, it's a graphics library. Just use some normal WINAPI method to do this. You could either create files like suggested (but can get strange when your application will crash, or after a power outage), or use memory mapped files or some other global objects to check if your app is stil running. You also could just check the process list to see if another copy is running. Another thing is to do a FindWindow with your window class, that's pretty easy and will work well. There are a lot of options, just search for this, it's a common question. (you could use some libraries for this, but since you are only targetting windows, I'd go with FindWindow.)

Cray
  • 2,396
  • 19
  • 29
  • Well, Qt is not only for GUI and abstracts away many other OS functionality, so until it is clear there is no way to do it in Qt, I would wait with resorting to WinAPI. – Christian Rau May 16 '12 at 07:20
  • 1
    Qt is much more than just a graphics library. It is a **cross platform** Application and UI framework. – pnezis May 16 '12 at 07:20
  • I know it's crossplatform, that's why I wrote that "since you are targetting windows". In that case I believe FindWindow is a much more clear solution than say, downloading new non-standard classes and using them. – Cray May 16 '12 at 07:24