How to get focused window width and height using Win32 API in WinForms C#

1 Answer

0 votes
using System.Runtime.InteropServices;

namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            [DllImport("user32.dll")]
            static extern IntPtr GetForegroundWindow();

            [DllImport("user32.dll", SetLastError = true)]
            static extern bool GetWindowRect(IntPtr hWnd, out Rectangle lpRect);

            Rectangle rect = new Rectangle();

            GetWindowRect(GetForegroundWindow(), out rect);

            int width = rect.Right - rect.Left;
            int height = rect.Bottom - rect.Top;

            textBox1.Text = width + " x " + height;
        }
    }
}



/*
run:
 
894 x 567
 
*/

 



answered Jan 15 by avibootz
edited Jan 15 by avibootz
...