Q: Why do you want to achieve this goal?
A: Because some programs need to use the computer above the hardware, such as the serial card collection and so on. In this case, the program can only be in memory
There is a copy, otherwise it will rob hardware resources, causing various problems.
Xxxxxxxxxxxxxxxxxxxxxx
There may be many ways to achieve this. But here I'm going to use the CreateMutex () function.
This function is defined inside the KERNEL32. This Chinese translation is to create an interlock.
Function Prototypes:
HANDLE CreateMutex (lpsecurity_attributes lpmutexattributes,//Pointer to security attribute BOOL Binitialowner,//Initialize owner of mutex object LPCTSTR Lpname//Pointer to the name of the mutex object);
Create a mutex (mutex)
return value
Long, if executed successfully, returns a handle to the mutex object;
Zero indicates an error. The GetLastError is set. Even if a valid handle is returned, GetLastError will be set to error_already_exists if the specified name already exists
Parameter table
Parameter type and description
Lpmutexattributes security_attributes, specifying a security_attributes structure, or passing a 0 value (declaring a parameter as a ByVal as Long and passing a 0 value), indicating the use of a default descriptor that does not allow inheritance
Binitialowner Long, set to True if the creation process wants to have the mutex immediately. A mutex can be owned by only one thread at a time
Lpname String that specifies the name of the mutex object. Creates an unnamed mutex object with vbNullString. If an event with this name already exists, the existing named mutex is opened. The name may not match the existing event, signal machine, wait timer, or file mapping
Xxxxxxxxxxxxxxxxxxxxxx
Example 1:
Set the application to allow only one instance **************************************************** HANDLE m_hmutex=createmutexa (null,true, m_ pszAppName); if (GetLastError () ==error_already_exists) {AfxMessageBox ("program started"); CloseHandle (M_hmutex); M_hmutex = Null;return FALSE;}//Set application to allow only one instance to end *************************************** *********
M_pszappname is the name of the program run, and M_pszappname is a public variable of the const char* type.
Xxxxxxxxxxxxxxxxxxxxxxx
Example 2:
Xxxxxxxxxxxxxxxxxxxxxxxxx
Objective: To have only one instance of the target program in-memory