If application is active


I am writing a program that sends keys to an application. So i need an if statement that says If notepad is active, run this code. Otherwise it will be sending keys when i'm doing anything!

Who is Participating?
Mike TomlinsonConnect With a Mentor Middle School Assistant TeacherCommented:
Here is how to determine if a NotePad instance currently has the focus:
Public Class Form1
    Private Sub Timer1_Tick_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        If AppHasFocus("NotePad") Then
            Label1.Text = "NotePad has Focus"
            Label1.Text = "NotePad does NOT have Focus"
        End If
    End Sub
    Private Declare Auto Function GetForegroundWindow Lib "user32.dll" () As IntPtr
    Private Function AppHasFocus(ByVal ExeNameWithoutExtension As String) As Boolean
        Dim activeHandle As IntPtr = GetForegroundWindow()
        For Each p As Process In Process.GetProcessesByName(ExeNameWithoutExtension)
            If p.MainWindowHandle.Equals(activeHandle) Then
                Return True
            End If
        Return False
    End Function
End Class

Open in new window

Sendkeys is somewhat unreliable at best.  You can use code like this to activate a window before sending keys.  (If the window is already active, no harm is done.)

Dim ProcessID As Integer = Shell("Notepad.exe", AppWinStyle.NormalFocus)
AppActivate(ProcessID)  'Also takes window text, like "Untitled - Notepad"
SendKeys.Send("This is a test")
matrix_aashAuthor Commented:
This is got an in-game thing so send keys is the only way unless you know the API for the game which is unlikley. Is there an if statement that checks to see if it is activated?
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Depends.  Could be done with Win32 API depending on how you are tracking the notepad window... How is notepad being run in the first place?  Does it have a window caption we can track?  Could there be more than one notepad window?
And why is AppActivate not appropriate rather than checking to see if the window is active?
Nice.  :)
matrix_aashAuthor Commented:
Thanks mate!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.