How to get form size using windows API in C#

1 Answer

0 votes
using System.Runtime.InteropServices;

namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool GetWindowRect(HandleRef hWnd, out RECT lpRect);

        [StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            public int Left;    // x upper left 
            public int Top;     // y upper left 
            public int Right;   // x lower right
            public int Bottom;  // y lower right
        }
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            RECT rect;
            if (GetWindowRect(new HandleRef(this, this.Handle), out rect)) {
                int width = rect.Right - rect.Left;
                int height = rect.Bottom - rect.Top;

                label1.Text = "width: " + width.ToString() + " height: " + height.ToString();
            }
        }
    }
}




/*
 * run:
 *
 * "width: 816 height: 489"
 * 
 */

 



answered Sep 5, 2023 by avibootz
edited Sep 6, 2023 by avibootz

Related questions

...