Q:

Check if an external program is the active window

I am making a form that uses the on screen keyboard and also I want the form to be closed if there is a click event outside of it.
To do so I used the dectivate event, but if I click on the on screen keyboard the deactivate event will be triggered for the form. So I am asking if there is a way to detect if the osk is the active window in order to put an if condition to not close the form in this case for the deactive event.
Is there any way to do so or a different way to manage the situation?

A:

You can use Platform Invocation (P/Invoke for short) to access the WinAPI functions GetForegroundWindow() and GetWindowThreadProcessId().
You can use GetForegroundWindow() in order to get the window handle of the currently focused/active window, then call GetWindowThreadProcessId() to get the process ID of that window. You can then use that ID to get an instance of the .NET Process class, with which you can easily access the process's name, etc.
To start with create a class called NativeMethods. In here we will declare all P/Invoked functions:
Imports System.Runtime.InteropServices

Public NotInheritable Class NativeMethods
    Private Sub New() 'Private constructor as we're not supposed to create instances of this class.
    End Sub

    <DllImport("user32.dll")> _
    Public Shared Function GetForegroundWindow() As IntPtr
    End Function

    <DllImport("user32.dll")> _
    Public Shared Function GetWindowThreadProcessId(ByVal hWnd As IntPtr, <Out()> ByRef lpdwProcessId As UInteger) As UInteger
    End Function
End Class

Then you can make a function in your code that uses these to get the active process:
Public Function GetActiveProcess() As Process
    Dim hWnd As IntPtr = NativeMethods.GetForegroundWindow()
    Dim ProcessID As UInteger = 0

    NativeMethods.GetWindowThreadProcessId(hWnd, ProcessID)

    Return If(ProcessID <> 0, Process.GetProcessById(ProcessID), Nothing)
End Function

Now you can use this like:
Dim ActiveProcess As Process = GetActiveProcess()

If ActiveProcess IsNot Nothing AndAlso ActiveProcess.ProcessName = "osk" Then
    'Active process is "osk", do something...
End If

