NGWS SDK Documentation  

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

EnumWindows

This example shows how unmanaged code, called via PInvoke, can call back again into managed code. It uses the familiar EnumWindows function from the Win32 API. Its signature is:

BOOL EnumWindows (WNDENUMPROC lpEnumFunc, LPARAM lParam)

When you call EnumWindows, the operating system steps through the list of windows on your computer. For each one, it calls the function you provide as the lpEnumFunc argument. You can do whatever you like in this function; typically, you might print out the name of the window. When you return from that function, the operating system continues its search.

The function you supply as the lpEnumFunc argument is known as a callback, for obvious reasons – the operating system calls you back for each window it finds. If your callback returns TRUE, the operating system continues its enumeration; if not, it stops.

Below is a tiny example of how you might use EnumWindows; this is written totally written in unmanaged, VC6:

#include <windows.h>
#include <stdio.h>

BOOL CALLBACK MyCallBack(HWND hwnd, LPARAM lParam) {
   printf("Window handle is %x \n", hwnd);
   return TRUE;
}

void main(void) { EnumWindows(MyCallBack, 0); }

Each window that EnumWindows finds, it calls MyCallBack. This simply prints out the value of the window handle, and returns TRUE to continue the enumeration.

We now rewrite this code to work with VC7, as follows:

#import <mscorlib.dll>

[delegate] bool CallBack(int hwnd, int lParam);  // a delegate type

bool Report(int hwnd, int lParam) {            // report the window handle
   Console::Write(L"Window handle is ");
   Console::WriteLine(hwnd);
   return true;
}

[sysimport(dll="user32")] 
extern "C" int EnumWindows(CallBack* x, int y);  // 

void main(void) { 
   CallBack* myCallBack = new CallBack(Report);
   EnumWindows(myCallBack, 0); 
}

We have added a [sysimport] directive to say that the EnumWindows function is to be found, as unmanaged code, in the user32.dll. Also, we have declared a delegate type, called “CallBack” which takes two int arguments and returns a bool. You can think of a delegate as like a function pointer in VC6.