VC语言

本类阅读TOP10

·VC++ 学习笔记(二)
·用Visual C++打造IE浏览器(1)
·每个开发人员现在应该下载的十种必备工具
·教你用VC6做QQ对对碰外挂程序
·Netmsg 局域网聊天程序
·Windows消息大全
·VC++下使用ADO编写数据库程序
·VC++学习笔记(四)
·非法探取密码的原理及其防范
·怎样在VC++中访问、修改注册表

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
创建只能运行一个程序的实例

作者:未知 来源:月光软件站 加入时间:2005-6-5 月光软件站

ps:您可以转载,但请注明出处;你可以修改,但请将修改结果告诉我。

《win95程序设计》 中说:

程序通过检查 hPrevInstance 参数就能够确定自身的其它执行实体是否正在运行。

在32位Windows版本中,该概念已被抛弃。传给WinMain的第二个参数总是NULL(定义为0)。

根据 hPrevInstance 创建只能运行一个实例的程序的方法可能只是针对 win16 吧?


参考 msdn 中的说法:


hPrevInstance
Handle to the previous instance of the application. For a Win32-based application, this parameter is always NULL.
If you need to detect whether another instance already exists, create a uniquely named mutex using theCreateMutex function. CreateMutex will succeed even if the mutex already exists, but theGetLastError function will return ERROR_ALREADY_EXISTS. This indicates that another instance of your application exists, because it created the mutex first.

写了一个只能运行一个实例的程序:

#include <windows.h>

int WINAPI WinMain(      
       HINSTANCE hInstance,
       HINSTANCE hPrevInstance,
       LPSTR lpCmdLine,
       int nShowCmd)
{
       CreateMutex(NULL, TRUE, "HelloWorld");
       if (GetLastError() == ERROR_ALREADY_EXISTS)
              return 0;

       MessageBox(
              NULL,
              "你好,世界",
              "欢迎",
              MB_OK
       );

       return 0;
}


后发现上述写法有漏洞,如果把这段代码

       CreateMutex(NULL, TRUE, "HelloWorld");
       if (GetLastError() == ERROR_ALREADY_EXISTS)
              return 0;


分别放在两个不同的程序 A,B 中,那么当 A 运行后,B 就不能运行了,而并没有达到原来的目的:只能运行一个A。

期待更好的方法。




相关文章

相关软件