How do I test if a window has focus (C#)?

I need to test if a Window has focus in C#. This window is an external application -- I am not looking to test if one of my forms is in focus. The only thing I know about the external application is it's process name (karafun.exe) and the title of the Window ("KaraFun").

Specifically, I'm looking to see when a karaoke song has ended, and the easiest way to do that is to see if the player control has focus. At this point I can load in a new song. So I guess what I need is code to: 1) Find the window by title (I used to know how to do this, but it's been a while) 2) Detect whether it has focus.

It would also be okay in this case to just get the title of the window with focus.
tylermenezesAsked:
Who is Participating?
 
Mike TomlinsonConnect With a Mentor Middle School Assistant TeacherCommented:
Here is an approach using Process.GetProcessesByName() and the GetForegroundWindow() API:
using System;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
 
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        public static extern IntPtr GetForegroundWindow();
        [DllImport("user32.dll")]
 
        private void button1_Click(object sender, EventArgs e)
        {
            Boolean focused = false;
            Process[] p = Process.GetProcessesByName("karafun");
            if (p.Length > 0)
            {
                if (p[0].MainWindowHandle.Equals(GetForegroundWindow()))
                {
                    focused = true;
                }
              
            }
            if (focused)
            {
                MessageBox.Show("KaraFun IS in focus.");
            }
            else
            {
                MessageBox.Show("KaraFun is NOT in focus.");
            }
        }
 
    }
}

Open in new window

0
 
anarki_jimbelConnect With a Mentor Commented:
I believe you can achieve that with pinvoke. See for examples:

http://www.pinvoke.net/default.aspx/user32/ShowWindow.html
0
 
tylermenezesAuthor Commented:
Thanks to both of you. Neither solution completely addressed my problem (the former was more of a reference and the latter returned true for any window that process had open) but they both helped me solve the problem. Thanks.
0
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.