I need to obtain the Excel 2013 x64 window handle from 64 bit VBA code running in a spreadsheet. There are a couple of options to do this:
Application.Hwnd
(MSDN Application.Hwnd Property (Excel))Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" ( _ ByVal lpClassName As String, _ ByVal lpWindowName As String) As LongPtr
The problem is that Application.Hwnd
returns a Long
, i.e. 32 bits (I've verified this with MsgBox TypeName(Application.Hwnd)
within a 64 bit environment), whereas FindWindow
returns a LongPtr
, which is 64 bits long in Office x64.
Does this mean that the Application.Hwnd
property can't be trusted to always be correct in a 64 bit environment?
Does this mean that the
Application.Hwnd
property can't be trusted to always be correct in a 64 bit environment?
No that is not true. The LongPtr
is just a variable data type which is a 4-bytes data type on 32-bit versions and an 8-byte data type on 64-bit versions of Office 2010.
You can read more about LongPtr
Here
In case the above link dies...
LongPtr
(Long integer on 32-bit systems, LongLong integer on 64-bit systems) variables are stored as signed 32-bit (4-byte) numbers ranging in value from -2,147,483,648 to 2,147,483,647
on 32-bit systems; and signed 64-bit (8-byte) numbers ranging in value from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
on 64-bit systems.
Note
LongPtr
is not a true data type because it transforms to a Long in 32-bit environments, or a LongLong
in 64-bit environments. Using LongPtr
enables writing portable code that can run in both 32-bit and 64-bit environments. Use LongPtr
for pointers and handles.
Suggested for further Reading:
Compatibility Between the 32-bit and 64-bit Versions of Office 2010
Followup from comments
However, I'm worried that since FindWindow can return a larger value, a window handle may exceed 32 bits at some stage. And if that's true, then Application.Hwnd would be unable to return the correct value. Or are you saying that a window handle will never exceed 32 bits?
The following link explains it beautifully. Interprocess Communication Between 32-bit and 64-bit Applications