Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleKeep track of the foreground application
DescriptionThis example shows how to keep track of the foreground application in Visual Basic 6 by using the GetForegroundWindow API function.
Keywordsforeground application, foreground window, foreground application, GetForegroundWindow
CategoriesAPI, Utilities
 
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 = _
        lvwFGWindow.ListItems.Add(Text:=Format$(Now, _
        "h:mm:ss"))
    list_item.SubItems(1) = GetWindowTitle(fg_hwnd)
    list_item.EnsureVisible
End Sub

' Return the window's title.
Private Function GetWindowTitle(ByVal window_hwnd As Long) _
    As String
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 & ">"
    Else
        ' Get the title.
        buf = Space$(length)
        length = GetWindowText(window_hwnd, buf, length)
        GetWindowTitle = Left$(buf, length)
    End If
End Function
 
You could modify the program to display its output in a text file instead of in a ListView.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated