November 14

Getting a Handle on hWnd

0  comments

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.

Loved this? Spread the word


About the Author

Jordan Goldmeier

Related posts

Microsoft Excel Visio Data Visualizer Add In for Excel: A Quick Guide

Read More

Highlighted Timeline Chart in Excel Without VBA: Raw and Uncut

Read More

Make Your Excel Spreadsheet into a Bitmap Image With This Excel Magic Trick

Read More

Excel Data Visualization: Presidential Approval Ratings with Slicers & Power Query – Chart Tricks

Read More
{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Subscribe to our newsletter now!

>