I'm trying to find the "active window" for a small screenshot program I'm building. I believe I just need its dimensions. I've tried googleing it forever now, but can't find anything that means anything to me.
I'd appreciate any help I can get, thanks!
Adam TurnerPosted Nov 21, 2007, 6:32 PM
AlanPosted Nov 21, 2007, 11:31 AM
Try this console app:
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Text;
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
public int Width
{
get{return Right - Left;}
}
public int Height
{
get{return Bottom - Top;}
}
}
class Program
{
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll")]
static extern int GetWindowRect(IntPtr hWnd, out RECT rect);
static void Main()
{
Console.WriteLine("You have 5 seconds to make another window active");
Console.WriteLine("otherwise dimensions will be for this console window");
Thread.Sleep(5000);
IntPtr hWnd = GetForegroundWindow();
int length = GetWindowTextLength(hWnd);
StringBuilder sb = new StringBuilder(length +1);
GetWindowText(hWnd, sb, sb.Capacity);
RECT rect;
GetWindowRect(hWnd, out rect);
Console.WriteLine("\nActive window title is '{0}'", sb.ToString());
Console.WriteLine("Width is {0} pixels",rect.Width);
Console.WriteLine("Height is {0} pixels", rect.Height);
}
}