我需要从电子表格中运行的 64 位 VBA 代码中获取 Excel 2013 x64 窗口句柄。有几个选项可以做到这一点:

  • 读取 Application.Hwnd ( MSDN Application.Hwnd Property (Excel) )
  • 调用 FindWindow,从 user32 导入,例如如此处接受的答案中所述:What are the differences between VBA 6.0 and VBA 7.0? :

  • 声明 PtrSafe 函数 FindWindow Lib "user32"别名 "FindWindowA"(_
    ByVal lpClassName As String, _
    ByVal lpWindowName As String) As LongPtr

    问题是 Application.Hwnd 返回一个 Long ,即 32 位(我已经在 64 位环境中用 MsgBox TypeName(Application.Hwnd) 验证了这一点),而 FindWindow 返回一个 LongPtr ,它在 Office x64 中是 64 位长。

    这是否意味着不能信任 Application.Hwnd 属性在 64 位环境中始终正确?

    最佳答案



    不,那不是真的。 LongPtr 只是一种可变数据类型,在 32 位版本上是 4 字节数据类型,在 64 位版本 Office 2010 上是 8 字节数据类型。

    您可以阅读有关 LongPtr Here 的更多信息

    如果上述链接失效...
    LongPtr(32 位系统上的长整数,64 位系统上的 LongLong 整数)变量存储为有符号的 32 位(4 字节)数字,其值范围从 32 位系统上的 -2,147,483,648 to 2,147,483,647 开始;和有符号的 64 位(8 字节)数字,其值范围从 64 位系统上的 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 开始。

    注意
    LongPtr 不是真正的数据类型,因为它在 32 位环境中转换为 Long,或者在 64 位环境中转换为 LongLong。使用 LongPtr 可以编写可在 32 位和 64 位环境中运行的 可移植代码 。将 LongPtr 用于指针和句柄。

    建议进一步阅读 :

    Compatibility Between the 32-bit and 64-bit Versions of Office 2010



    以下链接很好地解释了它。
    Interprocess Communication Between 32-bit and 64-bit Applications

    关于vba - Excel 的 Application.Hwnd 属性是否可用于 64 位 VBA?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30397294/

    10-11 02:21
    查看更多