The process list—Windows 95 view


You can create a collection of the current processes by calling the CreateProcess­List function, which will return a CVector of CProcess objects. The CVector class is an expandable array in a class wrapper. See “CVector Implementation” in Chapter 4. CreateProcessList works completely different for Windows 95 than for Windows NT, but this wrapper function hides the details so that you don’t have to worry about them.


When CreateProcessList is called under Windows 95, it calls ToolHelp32 functions to get a list of all the processes in the system. These functions will look familiar to those who used the 16-bit ToolHelp functions on which they are based. Here’s the code for the first half of CreateProcessList:

Function CreateProcessList() As CVector
Dim c As Long, f As Long, sName As String
Dim vec As CVector, process As CProcess
Set vec = New CVector

If MUtility.IsNT = False Then
' Windows 95 uses ToolHelp32 functions
Dim hSnap As Long, proc As PROCESSENTRY32
' Take a picture of current process list
hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
If hSnap = hNull Then Exit Function
proc.dwSize = Len(proc)
' Iterate through the processes
f = Process32First(hSnap, proc)
Do While f
' Put this process in vector and count it
sName = MUtility.StrZToStr(proc.szExeFile)
Set process = New CProcess
process.Create proc.th32ProcessID, MUtility.GetFileBaseExt(sName)
c = c + 1
Set vec(c) = process
f = Process32Next(hSnap, proc)
Loop

The big difference from the old 16-bit versions is that in 32-bit mode you have to take a snapshot of the system. Because Windows is a multitasking system, a process can disappear at any moment—including the moment you try to examine it. The CreateToolhelp32Snapshot function stores a copy of the system as it exists at the moment. After that, the Process32First and Process32Next can be used to iterate through the stored process list. These functions are equivalent to the TaskFirst and TaskNext functions of the 16-bit TOOLHELP.DLL. The CProcess class simply holds all the process data common to both Windows 95 and Windows NT—not much. The Create method initializes its properties.


This code illustrates an iteration pattern that will soon become familiar:
  1. Initialize the loop. In the example above, you create a snapshot and fill in the dwSize field to reassure Windows that you really have the right size structure. Details vary, but there’s usually some initialization required.

  2. Call Process32First (or Module32First or FindFirstFile or some other First function).

  3. Test at the top of the loop to handle the unlikely case of no items in the list.

  4. Do whatever the loop does. In this case, store the process name in a CVector.

  5. Call Process32Next (or some other Next function) until no more items are left.

The Windows NT version gives us an inside view because we’ll have to do by hand what the ToolHelp32 functions do automatically behind the scenes.