首页 > 解决方案 > 如何将焦点集中在另一个打开的应用程序上?

问题描述

我正在尝试在我的 VBA excel 代码中创建一个按钮,当按下它时,它将焦点放在另一个打开的 Windows 应用程序上并插入一些文本。我发现一些代码有点工作,但它不会切换到另一个应用程序,它会打开一个新应用程序。我怎样才能让它切换到已经打开的应用程序?

到目前为止,这是我的代码:

Public vPID As Variant
Private Sub CommandButton1_Click()
    vPID = Shell("C:\Windows\system32\notepad.exe", vbNormalFocus)
    Application.Wait (Now() + TimeValue("00:00:01"))
    SendKeys "test" + "{ENTER}"
End Sub

我是初学者,任何帮助将不胜感激!谢谢你

标签: excelvba

解决方案


这个问题在另一个线程中得到了回答:如何使用 FindWindow 在 VBA 中查找具有部分名称的可见或不可见窗口

我无法将您的问题标记为重复,因为提问者从未将答案选为正确的。

我在这个 vbforums.com 答案中找到了以下代码,并对其进行了增强以查找可见或不可见的窗口,因此希望能回答您的两个问题:

Option Explicit

Private Declare Function FindWindow Lib "User32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function GetWindowText Lib "User32" Alias "GetWindowTextA" (ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Private Declare Function GetWindowTextLength Lib "User32" Alias "GetWindowTextLengthA" (ByVal hWnd As Long) As Long
Private Declare Function GetWindow Lib "User32" (ByVal hWnd As Long, ByVal wCmd As Long) As Long
Private Declare Function IsWindowVisible Lib "User32" (ByVal hWnd As Long) As Boolean

Private Const GW_HWNDNEXT = 2

Private Sub Test()

    Dim lhWndP As Long
    If GetHandleFromPartialCaption(lhWndP, "Excel") = True Then
        If IsWindowVisible(lhWndP) = True Then
          MsgBox "Found VISIBLE Window Handle: " & lhWndP, vbOKOnly + vbInformation
        Else
          MsgBox "Found INVISIBLE Window Handle: " & lhWndP, vbOKOnly + vbInformation
        End If
    Else
        MsgBox "Window 'Excel' not found!", vbOKOnly + vbExclamation
    End If

End Sub

Private Function GetHandleFromPartialCaption(ByRef lWnd As Long, ByVal sCaption As String) As Boolean

    Dim lhWndP As Long
    Dim sStr As String
    GetHandleFromPartialCaption = False
    lhWndP = FindWindow(vbNullString, vbNullString) 'PARENT WINDOW
    Do While lhWndP <> 0
        sStr = String(GetWindowTextLength(lhWndP) + 1, Chr$(0))
        GetWindowText lhWndP, sStr, Len(sStr)
        sStr = Left$(sStr, Len(sStr) - 1)
        If InStr(1, sStr, sCaption) > 0 Then
            GetHandleFromPartialCaption = True
            lWnd = lhWndP
            Exit Do
        End If
        lhWndP = GetWindow(lhWndP, GW_HWNDNEXT)
    Loop

End Function

该代码搜索一个部分标题为“Excel”的窗口,并告诉您它是否找到它以及它是否是可见窗口。您应该能够根据自己的目的对其进行调整。


推荐阅读