Since I am a beginner, it may be a very basic question. I am starting DirectX 11, and while creating my first application, wWinMain was used, and while searching for difference
The prev instance parameter is there for 16-bit Windows compatibility. I think that was stated in the MSDN reference for WinMain, at least it used to be.
Raymond Chen's blog is almost entirely dedicated to discussing aspects of the Windows API that are "oddities" to us today. And fortunately, he has a blog post that answers this exact question:
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.
Of course, now that hPrevInstance
is irrelevant to the Windows API today except for compatibility reasons, MSDN recommends that you use a mutex to detect previous instances of an application.
A mutex stands for "mutual exclusion". You can refer to the MSDN documentation for CreateMutex()
. There are lots of examples of using mutexes to detect previous instances of applications, such as this one. The basic idea is to create a mutex with a unique name that you come up with, then attempt to create that named mutex. If CreateMutex()
failed with ERROR_ALREADY_EXISTS
, you know that an instance of your application was already launched.