我一直在尋找我的問題的答案,並沒有找到任何有關它,所以我來找你,看看你是否可以提供幫助。使用VB獲取當前活動並處於焦點的窗口的進程名稱。網
有沒有什麼辦法可以獲得當前活動的窗口的進程名稱,並使用VB進行焦點對話。淨?
在此先感謝
我一直在尋找我的問題的答案,並沒有找到任何有關它,所以我來找你,看看你是否可以提供幫助。使用VB獲取當前活動並處於焦點的窗口的進程名稱。網
有沒有什麼辦法可以獲得當前活動的窗口的進程名稱,並使用VB進行焦點對話。淨?
在此先感謝
您必須使用pinvoke。 GetForegroundWindow在前臺獲取窗口,GetWindowThreadProcessId獲取擁有它的進程的ID。剩下的很簡單,Process.GetProcessById()來查找進程。有關聲明,請訪問pinvoke.net網站。
這裏是代碼,以解決這個問題。我必須使用「GetForegroundWindow API」函數。
' 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