Getting a Handle on hWnd

Sometimes, you’ll want to programmatically take advantage of Windows outside the capabilities readily available through Visual Basic for Applications (VBA). For example, both eliminating the “Close”-button or creating a more opaque background on a window require the use of the Windows API.

Doing this in Visual Basic isn’t too hard, but there are some distinct differences between what’s readily available to programmers in Microsoft Office’s Visual Basic (VBA) compared to its virtual twin, Visual Basic 6.0, and its smarter, object-oriented younger brother VB.net. Specifically, UserForms in VBA do not contain methods to find their Windows handle, (aka, their hWnd).

And most window modifying APIs require the target window’s handle. Luckily, the Windows API also contains a function to find a given window’s hWnd, called FindWindow():


Public Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
(ByVal lpClassName As String, ByVal lpWindowName As String) As Long

So, to find your window’s handle, you’ll do something like this (assuming you’re coding within the UserForm).


hWnd = FindWindow("ThunderDFrame", me.caption)

Here, FindWindow() takes two arguments. First, the class name of the window for which you’re searching; and second, the window’s caption.

ThunderDFrame, huh?

I know, right? The UserForms in Excel are actually of the Windows class ThunderDFrame, which is the class for all UserFroms in Microsoft Office applications after 2002 (it was “ThunderXFrame” before that). I’ve looked online for a good explanation for the name but haven’t really found anything. Either way you’ll need to pass that into the first argument of FindWindow whenever you need a UserForm’s handle.

That’s all for now!

ps I’m working on a better stylesheet for when I display code.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s