Trying to get active window processID

darinf

New member
Joined
Apr 16, 2007
Messages
4
Programming Experience
Beginner
In my application I am trying to identify the process ID of the current active window.

I am using GetForegoundWindow to get the window identifier and then using GetWindowThreadProcessId to get the processID.

But the processID value it's returning is a non-existent PID. If I look at the Task manager, the PID's in my app do not match any of the PID's in the Task Manager.

If I try to get the process name, the app crashes since there is no PID that matches.

Here's the code sample:

VB.NET:
    Public Declare Function GetForegroundWindow Lib "user32" () As System.IntPtr
    Public Declare Auto Function GetWindowThreadProcessId Lib "user32" (ByVal hWnd As System.IntPtr, ByVal ProcessId As UInteger) As UInteger

    Public LastTitle As String
    Public Function RetCurTitle() As String
        Dim processID As UInteger
        'Dim p As Process
        Dim hWnd As IntPtr = GetForegroundWindow()
        processID = GetWindowThreadProcessId(hWnd, processID)
        layerNumCur.Text = processID
        Debug.WriteLine("Process ID = " & processID)
        'p = Process.GetProcessById(processID)
        'Caption = p.ProcessName
        'GetWindowText(hWnd, Caption, Caption.Capacity)
        Return processID
    End Function
Thanks in advance for your help,
-Darin Fong
 
VB.NET:
Declare Function GetForegroundWindow Lib "user32.dll" () As Int32

Declare Function GetWindowThreadProcessId Lib "user32.dll" ( _
    ByVal hwnd As Int32, _
    ByRef lpdwProcessId As Int32) As Int32
 
Public Function RetCurTitle() As String
    Dim processID As Int32
    GetWindowThreadProcessId(GetForegroundWindow(), processID)
    Return Process.GetProcessById(processID).MainWindowTitle
End Function
 
Back
Top