如何让应用程序只有一个实例
2015-03-12 19:57
330 查看
有一种方法,比较简单,用共享内存的形式。
#include <QMessageBox>
#include <windows.h>
const char *fn = "TT's Map";
//If the function succeeds, the return value is an open handle to the specified file mapping object.
//If the function fails, the return value is NULL.
HANDLE fd = OpenFileMapping( FILE_MAP_ALL_ACCESS, FALSE, (LPCWSTR)fn );
if( fd == NULL )
{
create( fn, 16 );
}
else
{
QMessageBox::information( NULL, "Error", "The programming is runing" );
return -1;
}
bool create( const char *fn, int len )
{
if( fn == NULL || len < 0 )
{
return false;
}
char *map = (char *)malloc( len );
if( !map )
{
abort();
}
if( *fn == '/' )
{
++fn;
}
if( len )
{
HANDLE fd = CreateFileMapping( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, len, (LPCWSTR)fn );
}
return true;
}
方法2:使用EXE程序的句柄
方法3:使用 OpenMutex (为现有的一个已命名互斥体对象创建一个新句柄 )和 CreateMutex
用 CloseHandle来关闭一个已经打开的Mutex。
#include <QMessageBox>
#include <windows.h>
const char *fn = "TT's Map";
//If the function succeeds, the return value is an open handle to the specified file mapping object.
//If the function fails, the return value is NULL.
HANDLE fd = OpenFileMapping( FILE_MAP_ALL_ACCESS, FALSE, (LPCWSTR)fn );
if( fd == NULL )
{
create( fn, 16 );
}
else
{
QMessageBox::information( NULL, "Error", "The programming is runing" );
return -1;
}
bool create( const char *fn, int len )
{
if( fn == NULL || len < 0 )
{
return false;
}
char *map = (char *)malloc( len );
if( !map )
{
abort();
}
if( *fn == '/' )
{
++fn;
}
if( len )
{
HANDLE fd = CreateFileMapping( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, len, (LPCWSTR)fn );
}
return true;
}
方法2:使用EXE程序的句柄
int main(int argc, char *argv[]) { QApplication a(argc, argv); QString str = "OMRON"; //OMRON.exe HWND hwnd = ::FindWindowW( NULL, str.toStdWString().c_str() ); if( hwnd ) //found { QMessageBox::warning(0, QObject::tr("Error"), QObject::tr("OMRON.exe is already running.")); QApplication::exit(); return; } return KernelExecute::Exec<OMRON_Main_Win>(a, true); }
方法3:使用 OpenMutex (为现有的一个已命名互斥体对象创建一个新句柄 )和 CreateMutex
用 CloseHandle来关闭一个已经打开的Mutex。
相关文章推荐
- 如何使应用程序只有一个实例在运行
- 如何确保只有一个应用程序实例在运行?
- 如何让应用程序只有一个实例在运行?
- 如何让应用程序只有一个实例在运行?
- C#如何让应用程序只有一个实例在运行
- 如何让Qt应用程序只有一个实例
- 如何使应用程序只有一个实例在运行
- 如何让应用程序只有一个实例在运行
- 如何让Qt应用程序只有一个实例
- 如何让Qt应用程序只有一个实例
- 如何让应用程序只有一个实例运行
- 关于"如何让应用程序只有一个实例在运行"的孟宪会的解决方法的疑问
- 使windows应用程序中只有一个实例
- 如何使应用程序只运行一个实例
- 如何用创建命名对象来判断应用程序是否已有一个实例在运行?
- Delphi中如何防止运行一个应用程序的多个实例
- 小文——在C# WinForm中如何使当前应用程序只允许启动一个实例
- 如何保证一个类只有一个实例(2)
- 保证应用程序只有一个实例运行.txt
- 如何保证一个类只有一个实例(1)