Excel成为Window Focus [英] Excel becoming Window Focus

查看:86
本文介绍了Excel成为Window Focus的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望找到一个事件,当Excel实例在Windows环境中成为焦点时,将在Excel VBA环境中触发。

I am looking to find an event that will trigger in the Excel VBA environment when an Excel instance becomes in focus in the Windows environment.

推荐答案

要实现这一目标,您必须依赖Windows API。 

To accomplish that you have to rely on Windows APIs. 

这里有一个有效的代码(已创建)来自这两个链接中的代码:  link1  和

link2
):

Here you have a working code (created from the codes found in these two links: link1 and link2):

Const SWP_NOSIZE = &H1
Const SWP_NOMOVE = &H2
Const HWND_TOPMOST = -1
Const HWND_NOTOPMOST = -2
Public Declare Function SetWindowPos Lib "user32" (ByVal hWnd As Long, ByVal hWndInsertAfter As Long, ByVal x As Long, ByVal y As Long, ByVal cx As Long, ByVal cy As Long, ByVal wFlags As Long) As Long
Public Declare Function FindWindow Lib "user32.dll" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long

Sub Button1_Click()
    'Bring the current Excel window to the front/back
    Call ForceWindowOnTop(GetExcelHandle, True)
End Sub

Public Sub ForceWindowOnTop(hWnd As Long, bTrueFalse As Boolean)
    Dim i
    If bTrueFalse = True Then
        i = SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE Or SWP_NOMOVE)
    Else
        i = SetWindowPos(hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOSIZE Or SWP_NOMOVE)
    End If
End Sub

Private Function GetExcelHandle() As Long
    GetExcelHandle = FindWindow("XLMAIN", "Microsoft Excel - " & ActiveWorkbook.Name)
End Function


这篇关于Excel成为Window Focus的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆