开发者

Getting Bounds of a specific Window

开发者 https://www.devze.com 2023-01-03 16:46 出处:网络
I have the following code : System.Drawing.Rectangle desktop_Rectangle = System.Windows.Forms.Screen.PrimaryScreen.Bounds开发者_运维技巧

I have the following code :

System.Drawing.Rectangle desktop_Rectangle = System.Windows.Forms.Screen.PrimaryScreen.Bounds

开发者_运维技巧

which gives me the Bounds of the Desktop.

I am now looking to get the Bounds of a specific Window using the caption of the Window.

Do I have to use Interop in order to accomplish that ?

any sample code would be greatly appreciated.

Thank you


namespace NativeInterop {
    using System.Runtime.InteropServices;

    public static partial class User32 {
        private const string DLL_NAME = "user32.dll";

        [StructLayout(LayoutKind.Sequential)]
        private struct RECT {
            int left, top, right, bottom;

            public Rectangle ToRectangle() {
                return new Rectangle(left, top, right - left, bottom - top);
            }
        }

        [DllImport(DLL_NAME, SetLastError = true)]
        public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, String className, String windowTitle);

        [DllImport(DLL_NAME)]
        private static extern bool GetClientRect(IntPtr hWnd, out RECT lpRect);

        public static Rectangle GetClientRect(IntPtr hWnd) {
            var nativeRect = new RECT();
            GetClientRect(hWnd, out nativeRect);
            return nativeRect.ToRectangle();
        }
    }
}

usage:

var handle = User32.FindWindowEx(IntPtr.Zero, IntPtr.Zero, String.Empty, "My Caption");
var rect = User32.GetClientRect(handle);


You are going to need FindWindow and GetWindowRect (or perhaps GetClientRect).

0

精彩评论

暂无评论...
验证码 换一张
取 消