如何让应用程序只有一个实例

来源:互联网 发布:如何关闭手机数据功能 编辑:程序博客网 时间:2024/05/12 14:29

有一种方法,比较简单,用共享内存的形式。

#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。

           

             




0 0
原创粉丝点击