VBA Code to Read the Active Program

2019-07-22 06:34发布

My hope is to have this macro continually record the name of whatever program is the current active program. I have a user form that runs a timer user a Macro that recalls itself every second. I would like it to record the name of the active window in that same macro and (if different from the last name) append that on to a descriptive string.

I had originally used the "Active window.caption" only to learn that it doesn't apply to other programs (such as chrome, word, or Outlook), But below is a chunk of my code.

If ActiveApp <> ActiveWindow.Caption Then           'look at active program for name
            ActiveApp = ActiveWindow.Caption                'if the last name is not the same as the current
            aapp2 = ThisWorkbook.Sheets("bts").Range("b13").Value & "|" & ActiveApp & ": " & Format(dteElapsed, "hh:mm:ss")
            'updates the descriptive string
            ThisWorkbook.Sheets("bts").Range("b13").Value = aapp2
        End If

Whole Macro:

Sub timeloop()


If ThisWorkbook.Sheets("BTS").Range("b7").Value = "" Then 'the location on theworksheet that time is stored
    ThisWorkbook.Sheets("BTS").Range("b7").Value = Time '
    ThisWorkbook.Sheets("BTS").Range("b12").Value = Date
    End If



    dteStart = ThisWorkbook.Sheets("BTS").Range("b7").Value
    dteFinish = Time
    DoEvents
    dteElapsed = dteFinish - dteStart
    If Not booldead = True Then 'See if form has died

       TimeRun.Label1 = Format(dteElapsed, "hh:mm:ss")
        If ActiveApp <> ActiveWindow.Caption Then           'look at active program for name
            ActiveApp = ActiveWindow.Caption                'if the last name is not the same as the current
            aapp2 = ThisWorkbook.Sheets("bts").Range("b13").Value & "|" & ActiveApp & ": " & Format(dteElapsed, "hh:mm:ss")
            'updates the descriptive string
            ThisWorkbook.Sheets("bts").Range("b13").Value = aapp2
        End If


    Else
        Exit Sub
    End If
    Alerttime = Now + TimeValue("00:00:01")
Application.OnTime Alerttime, "TimeLoop"
End Sub

1条回答
We Are One
2楼-- · 2019-07-22 07:23

To get the Name of the active application/window, you'll need to use API calls.

This Question on the office site should help you.

Public Declare Function GetForegroundWindow Lib "user32" _
    Alias "GetForegroundWindow" () As Long
Public Declare Function GetWindowText Lib "user32" _
    Alias "GetWindowTextA" (ByVal hwnd As Long, _
    ByVal lpString As String, ByVal cch As Long) As Long

Sub AAA()
    Dim WinText As String
    Dim HWnd As Long
    Dim L As Long
    HWnd = GetForegroundWindow()
    WinText = String(255, vbNullChar)
    L = GetWindowText(HWnd, WinText, 255)
    WinText = Left(WinText, InStr(1, WinText, vbNullChar) - 1)
    Debug.Print L, WinText
End Sub

Running the AAA sub should print the title of the active window to the debug console.

查看更多
登录 后发表回答