Windows客户端开发--只允许有一个实例运行

没有人会漫无目的地旅行,那些迷路者是希望迷路。--------《岛上书店》

一个pc可以同时运行几个qq,但是只允许运行一个微信。

所以,今天就跟大家分享一下,如何确保你开发的windows客户端只能同时运行一个实例,或是叫进程。

使用mutex
OpenMutex函数为现有的一个已命名互斥体对象创建一个新句柄。
即在main函数中创建一个互斥量:

WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{try {// Try to open the mutex.HANDLE hMutex = OpenMutex(MUTEX_ALL_ACCESS, 0, "MyApp1.0");if (!hMutex)// Mutex doesn’t exist. This is// the first instance so create// the mutex.hMutex = aCreateMutex(0, 0, "MyApp1.0");else// The mutex exists so this is the// the second instance so return.return 0;Application->Initialize();Application->CreateForm(__classid(TForm1), &Form1);Application->Run();// The app is closing so release// the mutex.ReleaseMutex(hMutex);}catch (Exception &exception) {Application->ShowException(&exception);}return 0;
}

使用CreateEvent
CreateEvent是一个Windows API函数。它用来创建或打开一个命名的或无名的事件对象。

bool CheckOneInstance()
{HANDLE  m_hStartEvent = CreateEventW( NULL, FALSE, FALSE, L"Global\\CSAPP" );if(m_hStartEvent == NULL){CloseHandle( m_hStartEvent ); return false;}if ( GetLastError() == ERROR_ALREADY_EXISTS ) {CloseHandle( m_hStartEvent ); m_hStartEvent = NULL;// already exist// send message from here to existing copy of the applicationreturn false;}// the only instance, start in a usual wayreturn true;
}

使用FindWindow
FindWindow这个函数检索处理顶级窗口的类名和窗口名称匹配指定的字符串。

HWND hWnd = ::FindWindow(LPCTSTR lpClassName, LPCTSTR lpWindowName);
if (hWnd != null)
{ShowWindow(hWnd, SW_NORMAL);return (1);
}

使用CreateSemaphore
创建一个新的信号量

CreateSemaphore(NULL, TRUE, TRUE, "MYSEMAPHORE");
if (GetLastError() == ERROR_ALREADY_EXISTS)
{return FALSE
}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部