如何运行只有一个应用程序的实例

我有一个应用程序使用套接字连接来发送和接收来自另一个应用程序的数据。 在创build套接字时,它使用端口4998。

那是我的问题所在。 一旦我开始我的应用程序套接字开始使用端口4998.所以,如果我想再次执行应用程序,然后我得到套接字绑定错误。

所以我想限制我的应用程序实例。 这意味着,如果应用程序已经在运行,并且有人试图通过点击exe或快捷方式图标再次运行应用程序,则不应该运行该程序,而应该将现有的应用程序置于Top。

你可以使用命名的互斥体。

来自文章的代码示例:

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 = CreateMutex(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; } 

/ *我找到了必要的编辑工作。 增加了一些额外的代码和编辑所需要的。 目前的一个对我来说是完美的。 感谢Kirill V. Lyadvinsky和Remy Lebeau的帮助!

* /

 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 application return false; } // the only instance, start in a usual way return true; } 

/ *以上代码即使在试图打开第二个实例FROM A不同的登录使用其实例运行第一个登录打开。 * /

在开始时创建命名事件并检查结果。 如果事件已经存在,请关闭应用程序。

 BOOL CheckOneInstance() { m_hStartEvent = CreateEventW( NULL, TRUE, FALSE, L"EVENT_NAME_HERE" ); if ( GetLastError() == ERROR_ALREADY_EXISTS ) { CloseHandle( m_hStartEvent ); m_hStartEvent = NULL; // already exist // send message from here to existing copy of the application return FALSE; } // the only instance, start in a usual way return TRUE; } 

关闭应用程序出口处的m_hStartEvent

你还没有办法检查你的应用程序是否正在运行? 谁需要一个互斥体,如果端口已经被使用,你就知道该应用程序正在运行!

当您的应用程序初始化时,创建一个互斥体。 如果它已经存在,找到现有的应用程序,并把它放在前台。 如果应用程序的主窗口具有固定标题,则使用FindWindow很容易找到。

 m_singleInstanceMutex = CreateMutex(NULL, TRUE, L"Some unique string for your app"); if (m_singleInstanceMutex == NULL || GetLastError() == ERROR_ALREADY_EXISTS) { HWND existingApp = FindWindow(0, L"Your app's window title"); if (existingApp) SetForegroundWindow(existingApp); return FALSE; // Exit the app. For MFC, return false from InitInstance. }