[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2824
  • Last Modified:

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.
0
tylermenezes
Asked:
tylermenezes
2 Solutions
 
anarki_jimbelCommented:
I believe you can achieve that with pinvoke. See for examples:

http://www.pinvoke.net/default.aspx/user32/ShowWindow.html
0
 
Mike TomlinsonMiddle 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
 
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

Featured Post

Restore individual SQL databases with ease

Veeam Explorer for Microsoft SQL Server delivers an easy-to-use, wizard-driven interface for restoring your databases from a backup. No expert SQL background required. Web interface provides a complete view of all available SQL databases to simplify the recovery of lost database

Tackle projects and never again get stuck behind a technical roadblock.
Join Now