gpt4 book ai didi

c++ - 为什么 prevInstance 存在于 WinMain 和 wWinMain 中,如果它始终为 NULL

转载 作者:可可西里 更新时间:2023-11-01 18:16:28 26 4
gpt4 key购买 nike

由于我是初学者,这可能是一个非常基础的问题。我正在启动 DirectX 11,在创建我的第一个应用程序时,使用了 wWinMain,在搜索 WinMain 和 wWinMain 之间的区别时,我遇到了这个参数 prevInstance。

prevInstance 根据 MSDN 始终为 null,并且由于它始终为 null,为什么它存在(因为认为创建者不会给出无用参数是合乎逻辑的)。并且(引自书中),

if you need a way to determine whether a previous instance of the application is already running, the documentation recommends creating a uniquely named mutex using CreateMutex. Although the mutex will be created, the CreateMutex function will return ERROR_ALREADY_EXISTS.

什么是互斥量,以及如何使用它(一个好的链接就足够了)。看起来需要一个方法来查找应用程序的另一个实例是否存在,prevInstance 应该有一个指针或对它的引用,但显然不是这种情况,因为它是空的。为什么会这样,prevInstance的作用是什么?

最佳答案

Raymond Chen's blog几乎完全致力于讨论 Windows API 的某些方面,这些方面对我们今天来说是“奇怪的”。幸运的是,他有一个 blog post回答了这个确切的问题:

In 16-bit Windows there was a function called GetInstanceData. This function took an HINSTANCE, a pointer, and a length, and copied memory from that instance into your current instance. (It's sort of the 16-bit equivalent to ReadProcessMemory, with the restriction that the second and third parameters had to be the same.)

...

This was the reason for the hPrevInstance parameter to WinMain. If hPrevInstance was non-NULL, then it was the instance handle of a copy of the program that is already running. You can use GetInstanceData to copy data from it, get yourself up off the ground faster. For example, you might want to copy the main window handle out of the previous instance so you could communicate with it.

Whether hPrevInstance was NULL or not told you whether you were the first copy of the program. Under 16-bit Windows, only the first instance of a program registered its classes; second and subsequent instances continued to use the classes that were registered by the first instance. (Indeed, if they tried, the registration would fail since the class already existed.) Therefore, all 16-bit Windows programs skipped over class registration if hPrevInstance was non-NULL.

The people who designed Win32 found themselves in a bit of a fix when it came time to port WinMain: What to pass for hPrevInstance? The whole module/instance thing didn't exist in Win32, after all, and separate address spaces meant that programs that skipped over reinitialization in the second instance would no longer work. So Win32 always passes NULL, making all programs believe that they are the first one.

当然,既然 hPrevInstance 与当今的 Windows API 无关,除非出于兼容性原因,MSDN 建议您使用互斥锁来检测应用程序的先前实例。

互斥锁代表“互斥”。可以引用the MSDN documentation对于 CreateMutex()。有很多使用互斥锁来检测以前的应用程序实例的示例,such as this one .基本思想是创建一个具有您想出的唯一名称的互斥锁,然后尝试创建该命名的互斥锁。如果 CreateMutex() 失败并返回 ERROR_ALREADY_EXISTS,您就知道您的应用程序实例已经启动。

关于c++ - 为什么 prevInstance 存在于 WinMain 和 wWinMain 中,如果它始终为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7458436/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com