jgiunta
jgiunta

Reputation: 721

Get the process name of the window that is currently active and in focus using VB. Net

I've been looking for the answer to my question and have not found anything about it, so I come to you to see if you can help.

Is there any way to get the process name of the window that is currently active and in focus using VB. Net?

Thanks in advance

Upvotes: 1

Views: 5469

Answers (2)

Hans Passant
Hans Passant

Reputation: 941465

You'll have to use pinvoke. GetForegroundWindow to get the window in the foreground, GetWindowThreadProcessId to get the ID of the process that owns it. The rest is easy, Process.GetProcessById() to find the process. Visit the pinvoke.net website for the declarations.

Upvotes: 4

jgiunta
jgiunta

Reputation: 721

Here is the code, to solve this problem. I must use "GetForegroundWindow API" function.

' The hWnd of the most recently found window.
Private m_LastHwnd As Integer

Private Sub tmrGetFgWindow_Tick(ByVal sender As _
    System.Object, ByVal e As System.EventArgs) Handles _
    tmrGetFgWindow.Tick
    ' Get the window's handle.
    Dim fg_hwnd As Long = 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.
    Dim list_item As System.Windows.Forms.ListViewItem
    list_item = _
        lvwFGWindow.Items.Add(Text:=Now.ToString("h:mm:ss"))
    list_item.SubItems.Add(GetWindowTitle(fg_hwnd))
    list_item.EnsureVisible()
End Sub

' Return the window's title.
Private Function GetWindowTitle(ByVal window_hwnd As _
    Integer) As String
    ' See how long the window's title is.
    Dim length As Integer
    length = GetWindowTextLength(window_hwnd) + 1
    If length <= 1 Then
        ' There's no title. Use the hWnd.
        Return "<" & window_hwnd & ">"
    Else
        ' Get the title.
        Dim buf As String = Space$(length)
        length = GetWindowText(window_hwnd, buf, length)
        Return buf.Substring(0, length)
    End If
End Function

Upvotes: 2

Related Questions