Control the number of started programs (Limit Multiple game launches) and more
Introduction:
In the process of using software on the PC end, developers sometimes need to limit the number of programs to be started. For example, to limit the number of started programs on a single PC end, or to count the number of programs started on the PC end, it is clear that a "counter" is needed to count the number of programs running.
How to count multiple programs
When you start multiple programs, because the program is affiliated with different processes and the conventional counting method is not available, it is difficult to count the number of programs started. The following describes a common method-using mutex:
# Include "stdafx. h "# include" windows. h "# include <iostream> using namespace std; class MaxClientLimitInstance {public: static bool Lock (int MaxInstanceCount) {int ret = 0; for (int I = 0; I <MaxInstanceCount; ++ I) {HANDLE h =: CreateMutex (0, 1, L "test program"); if (GetLastError () = 0) {m_Handle = h; break ;} else {CloseHandle (h); ret ++; }}return ret <MaxInstanceCount;} static void UnLock () {if (m_Handle! = NULL) {ReleaseMutex (m_Handle); CloseHandle (m_Handle) ;}} static HANDLE m_Handle ;}; HANDLE MaxClientLimitInstance: m_Handle = 0; int _ tmain (int argc, _ TCHAR * argv []) {int MaxNumber = 1; if (! MaxClientLimitInstance: Lock (MaxNumber) {cout <"You have already run a program! This program will be closed. "<endl; system (" pause "); return 0 ;}else {cout <" Run program success! "<Endl;} system (" pause "); // <wait for user input. In a game program, the following logic can be executed in the main loop of the game :: unLock (); // <Note: After "waiting for user input", ReleaseMutex; otherwise, the mutex is released and cannot return 0 as expected ;}
Running result
As for the limit on the number of started programs, writing in the Code is obviously not an elegant practice. A more common practice is to pass in the program through the command line parameters of the started program. When the number of restricted programs needs to be changed, you can only modify the command line to meet the requirements without modifying the code.