Hello!

I want my application to know, in the main(...) method preferentially even before starting the QApplication, if an instance of the same application is already running.

Till now I have being doing this by using the following method:

Qt Code:
  1. /*!
  2.  * \brief getOthermShare tells if there is another mShare opened in this machine.
  3.  * \return
  4.  */
  5. bool getOthermShare()
  6. {
  7. bool mshare_detectado = false;
  8. // Get the list of process identifiers
  9. DWORD aProcesses[1024], cbNeeded, cProcesses;
  10.  
  11. //Tenta 10 vezes capturar os processos; se nao conseguir, fecha (rever isso aqui!)
  12. for (int aaa = 0; aaa < 10; aaa++)
  13. {
  14. if (EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
  15. break;
  16. else if (aaa == 9)
  17. {
  18. QMessageBox::warning(NULL,QMessageBox::tr("Error"),QMessageBox::tr("A fatal error ocurred. Please close down your application and try again.\nIf the problem persists, enter in contact with "
  19. "the support team."));
  20. return false;
  21. }
  22. }
  23.  
  24. // Calculate how many process identifiers were returned.
  25. cProcesses = cbNeeded / sizeof(DWORD);
  26.  
  27. // Discover the name and process identifier for each process.
  28. for (unsigned int i = 0; i < cProcesses; i++ )
  29. {
  30. if( aProcesses[i] != 0 )
  31. {
  32. TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
  33.  
  34. // Get a handle to the process.
  35. HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_ALL_ACCESS | READ_CONTROL |
  36. PROCESS_VM_READ,
  37. FALSE, aProcesses[i] );
  38.  
  39. // Get the process name.
  40. if (NULL != hProcess )
  41. {
  42. HMODULE hMod;
  43. DWORD cbNeeded;
  44.  
  45. if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod),
  46. &cbNeeded) )
  47. {
  48. GetModuleBaseName( hProcess, hMod, szProcessName,
  49. sizeof(szProcessName)/sizeof(TCHAR) );
  50. }
  51.  
  52. #ifdef Q_OS_WIN
  53. #ifdef UNICODE
  54.  
  55. if (QString::fromUtf16((ushort*)szProcessName).section(".",0,0) == "mShare")
  56. {
  57. if (!mshare_detectado)
  58. mshare_detectado = true;
  59. else
  60. {
  61. CloseHandle( hProcess );
  62. return true;
  63. }
  64. }
  65. #endif
  66. #endif
  67. // Release the handle to the process.
  68. CloseHandle( hProcess );
  69. }
  70. }
  71. }
  72.  
  73. return false;
  74. }
To copy to clipboard, switch view to plain text mode 

which obviously have two problems: first, it works only for Windows, and second, its kinda akward :P

So I'ld like to know if there is a "Qt way" of doing the same thing with the advantage of being platform independent. I noticed the solution shown at [http://www.qtcentre.org/wiki/index.p...leApplication], but I must say I didn't like that way :P Is there another solution? (and one that don't use anything extern to the application, such as a file that is written with "1" when the software is opened or the like)


Thanks,

Momergil