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。
期待更好的方法。

|