Authored in 2010
Capturing process information from the currently active application can be useful when coding interactions between applications.
The code for getting this information is relatively simple, though it involves a few different Windows API calls.
First we need to declare the Windows API functions, which are done as follows. Enter the following code in a class of your choice:
Declare Function GetForegroundWindow Lib "user32.dll" () As Int32
Declare Function GetWindowThreadProcessId Lib "user32.dll" (ByVal hwnd As Int32, ByRef lpdwProcessId As Int32) As Int32
The "GetForegroundWindow" API function is used to get a handle to the Foreground window. The foreground window is just the main window of the application that is currently in the foreground, i.e. The currently active application.
The "GetWindowThreadProcessID" API function, uses the handle returned from "GetForegroundWindow" in order to retrieve the ID of that window's process.
The following function returns a .NET process object, using the two above API functions. Place the code in the same class as the API function declarations from above.
Private Function GetActiveAppProcess() As Process
Dim activeProcessID As IntPtr
'Getting handle of foreground window (the active application) and returning it to activeProcessHandle
GetWindowThreadProcessId(GetForegroundWindow(), activeProcessID)
Return Process.GetProcessById(pActiveProcessID)
End Function
To use the function, simply call it somewhere in your code and use the returned process object.
Private Sub Timer1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim activeProcess as Process=GetActiveAppProcess()
Debug.write("Name of the process of the currently active application is: " & activeProcess.name)
End Sub
In the above sample, I use a timer object to capture the active application. I do this, as usually you do not want the process information of your own application. This can be achieved much easier using System.Diagnostics.Process.GetCurrentProcess(). Instead you'd often be interested in whatever application is active for the user, and do something with that information. For this purpose, a timer could be a useful approach by checking the active application every second or so.