获得特定窗口的界限

时间:2010-06-17 19:53:58

标签: c# graphics

我有以下代码:

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

它给了我桌面的界限。

我现在想要使用窗口的标题来获取特定窗口的边界。

我是否必须使用Interop才能实现这一目标?

非常感谢任何示例代码。

谢谢

2 个答案:

答案 0 :(得分:4)

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();
        }
    }
}

用法:

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

答案 1 :(得分:0)

您需要FindWindowGetWindowRect(或者GetClientRect)。

相关问题