我正在使用QT for Windows开发应用程序,我遇到以下问题: 1.一些用户正在打开同一应用程序的多个实例,这是不允许的。 如何控制每个用户只打开一次应用程序,而不使用qtsingleapplication?
答案 0 :(得分:0)
快速而肮脏的方法是创建一个锁文件。如果锁定文件存在且进程处于活动状态,则新实例将退出。下面给出了一个粗略且未经检查的例子。
bool isProcessRunning( DWORD processID, std::string processName) {
TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
// Get a handle to the process.
HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID );
// Get the process name.
if ( NULL != hProcess ) {
HMODULE hMod;
DWORD cbNeeded;
if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod), &cbNeeded) )
GetModuleBaseName( hProcess, hMod, szProcessName, sizeof(szProcessName)/sizeof(TCHAR) );
}
// Compare process name with your string
bool matchFound = !_tcscmp(szProcessName, processName.c_str() );
// Release the handle to the process.
CloseHandle( hProcess );
return matchFound;
};
void lockApp() {
/*
*
* lockApp() -> None
*
* Lock app to one instance
*
* @return None
*
*/
/* Flags */
int pid = -1;
bool procRunning = true;
/* App Lock file: Name and Location */
QString lockFile = QDir::temp().filePath( "MyAppName.lock" );
// check for the lock file and see if its stale.
if ( QFileInfo( lockFile ).exists() ) {
// OK, lock exists. Now, check if it is stale!
QFile pidFile( lockFile );
pidFile.open( QFile::ReadOnly );
pid = pidFile.readAll().toInt();
pidFile.close();
// if /proc/pid doesnot exist, we have a stale lock
if( isProcessRunning( pid, "MyAppName" ) ) {
procRunning = false;
QFile::remove( lockFile );
}
}
else {
procRunning = false;
}
if ( procRunning ) {
qApp->quit();
exit( 0 );
}
QFile pidFile( lockFile );
pidFile.open( QFile::WriteOnly );
pidFile.write( qPrintable( QString::number( qApp->applicationPid() ) ) );
pidFile.close();
};
第一个功能来自这里。 https://stackoverflow.com/a/13635127/1233513