016 程序单开应用 8

实现限制程序多开

 

测试代码

创建第一个程序ProcessMutexDemo.exe

 1 #include <windows.h>
 2 #include <stdio.h>
 3 int main()
 4 {
 5     HANDLE hMutex = CreateMutex(NULL, TRUE, TEXT("Demo"));
 6     //OpenMutex打开已经存在的
 7     //OpenMutex()
 8     WaitForSingleObject(hMutex,INFINITE);
 9     if(hMutex == NULL)
10     {
11         printf("hMutex == NUL");
12     }
13     while(true)
14     {
15         Sleep(1000);
16     }
17     return 0;
18 }

 

创建第二个程序ProcessMutexDemoB.exe

 1 #include <windows.h>
 2 #include <stdio.h>
 3 int main()
 4 {
 5     HANDLE hMutex = CreateMutex(NULL, TRUE, TEXT("Demo"));
 6     //OpenMutex打开已经存在的
 7     //OpenMutex()
 8     if(GetLastError() == ERROR_ALREADY_EXISTS)
 9     {
10         printf("Is Extsts....");
11     }
12     while(true)
13     {
14         Sleep(1000);
15     }
16     return 0;
17 
18 }

 

测试结果

 

单个的实现方法

 1 #include <windows.h>
 2 #include <stdio.h>
 3 int main()
 4 {
 5     HANDLE hMutex = CreateMutex(NULL, TRUE, TEXT("Demo"));
 6 
 7     if(GetLastError() == ERROR_ALREADY_EXISTS)
 8     {
 9         printf("Is Extsts....");
10     }
11     WaitForSingleObject(hMutex,INFINITE);
12     if(hMutex == NULL)
13     {
14         printf("hMutex == NUL");
15     }
16     while(true)
17     {
18         Sleep(1000);
19     }
20     return 0;
21 }

 

posted @ 2017-07-11 09:17  ☆﹎夜﹎☆  阅读(181)  评论(0编辑  收藏  举报