A Basic CWindow class


WinWatch looks at windows from the outside and must do things the Windows Way, not the Basic Way. But this was a choice, not a requirement. It’s not impossible to access window features in an object-oriented way; all you need is a CWindow class written in Visual Basic. I actually wrote this class, but WinWatch doesn’t use it. Sometimes the functional philosophy is more convenient than the object religion.


You might find it amusing to check out CWindow on the companion CD, in the TWINDOW.VBP project. This class might even work for some of your projects. I’ll describe the design, but frankly, I wrote CWindow more to show that it could be done than as a practical tool. It simply wraps the more common API functions related to windows in a thin layer.


CWindow has only one private member variable, hWnd. You initialize this internal variable using the Handle property, but you don’t have to use the name Handle because it is the default property:

Dim wnd As New CWindow
wnd = Me.hWnd

You can also initialize the object with one of a variety of Create methods:

wnd.CreateFromPoint x, y                      ‘ WindowFromPoint
wnd.CreateFromFind “MyClass", “My Title” ‘ FindWindow
wnd.CreateFromActive ‘ GetActiveWindow

Once you initialize the object, you can get and read properties or call methods:

wnd.Caption = “My Title”                      ‘ GetWindowText
wnd.Capture True ‘ SetCapture
wnd.Capture False ‘ ReleaseCapture
sClass = wnd.ClassName ‘ GetClassName

Most of these methods and properties have one-line implementations. Here are a couple to give you the idea:

Private hWnd As Long
Public Property Get Handle() As Long
Handle = hWnd
End Property

Public Property Let Handle(ByVal hWndA As Long)
If IsWindow(hWndA) Then hWnd = hWndA Else hWnd = hNull
End Property

I started writing new methods and properties as fast as I could type them, but I gave up after a while because I could see that the class wasn’t going to be much use. Feel free to finish the implementation. You can see my first cut in Figure 6-2 on the following page.


The problem with CWindow is that it adds a layer of complication and inefficiency without offering much advantage. For example, imagine that you have some code that retrieves a window handle and then uses it to get some data about the window. Which of the following is easier?

With wnd
f = .CreateFromFind(“SciCalc”)
fVisible = .Visible
sTitle = .Caption
idProc = .ProcID
End With


Figure 6-2. First draft of the CWindow class.


And here’s the alternative:

hWnd = FindWindow(“SciCalc”)
fVisible = IsWindowVisible(hWnd)
sTitle = WindowTextFromWnd(hWnd)
idProc = ProcIDFromWnd(hWnd)

Either way, you must write the declarations for the Windows API functions and wrap un-Basic functions in Visual Basic wrappers (as you’ll see later). But you’re doing the same work—just packaging it differently.