|Title||Keep track of the foreground application|
|Description||This example shows how to keep track of the foreground application in Visual Basic 6 by using the GetForegroundWindow API function.|
|Keywords||foreground application, foreground window, foreground application, GetForegroundWindow|
Recently I wanted a simple program to keep track of what I was doing throughout the day. Here's the result.
When the program's Timer fires, the code uses the GetForegroundWindow API function to get the handle of the foreground window. It uses the GetWindowText API function to get the window's caption and displays it and the time in a ListView control.
' The hWnd of the most recently found window.
Private m_LastHwnd As Long
Private Sub tmrGetFgWindow_Timer()
Dim fg_hwnd As Long
Dim list_item As ListItem
' Get the window's handle.
fg_hwnd = GetForegroundWindow()
' If this is the same as the previous foreground window,
' let that one remain the most recent entry.
If m_LastHwnd = fg_hwnd Then Exit Sub
m_LastHwnd = fg_hwnd
' Display the time and the window's title.
Set list_item = _
list_item.SubItems(1) = GetWindowTitle(fg_hwnd)
' Return the window's title.
Private Function GetWindowTitle(ByVal window_hwnd As Long) _
Dim length As Long
Dim buf As String
' See how long the window's title is.
length = GetWindowTextLength(window_hwnd) + 1
If length <= 1 Then
' There's no title. Use the hWnd.
GetWindowTitle = "<" & window_hwnd & ">"
' Get the title.
buf = Space$(length)
length = GetWindowText(window_hwnd, buf, length)
GetWindowTitle = Left$(buf, length)
You could modify the program to display its output in a text file instead of in a ListView.