1

I've created some global Hot keys for my application and I want them to work only if my application is active. (It should not work if my application is not the active form).

So how can I check if my C# winform application is the active form among all the other windows applications?

I tried

if(this.Focused)
  //Do somthing

But it's not working

Tharif
  • 13,794
  • 9
  • 55
  • 77
Ghasem
  • 14,455
  • 21
  • 138
  • 171

2 Answers2

0

Try this:

[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int GetWindowThreadProcessId(IntPtr handle, out int processId);

public static bool Activates()
{
    var x = GetForegroundWindow();
    if (x == IntPtr.Zero) {
        return false;      
    }

    var y = Process.GetCurrentProcess().Id;
    int i;
    GetWindowThreadProcessId(x, out i);

    return i == y;
}

You can also refer: C#: Detecting which application has focus

Community
  • 1
  • 1
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

You can use Windows API function GetForegroundWindow and GetWindowText.

GetForegroundWindow :

The GetForegroundWindow function returns a handle to the window with which the user is currently working.

GetWindowText:

The GetWindowText function copies the text of the specified window's title bar (if it has one) into a buffer.

Add below code to declare API functions :

[ DllImport("user32.dll") ]
        static extern int GetForegroundWindow();

[ DllImport("user32.dll") ]
        static extern int GetWindowText(int hWnd, StringBuilder text, int count);

Start a timer :

private void timer1_Tick(object sender, System.EventArgs e)
        {
            GetActiveWindow();
        }

Active window function :

private void GetActiveWindow()
    {

        const int nChars = 256;
        int handle = 0;
        StringBuilder Buff = new StringBuilder(nChars);

        handle = GetForegroundWindow();

        if ( GetWindowText(handle, Buff, nChars) > 0 )
        {
            this.captionWindowLabel.Text = Buff.ToString();
            this.IDWindowLabel.Text = handle.ToString();
        }

    }
Tharif
  • 13,794
  • 9
  • 55
  • 77