为什么我的高度和宽度为0?

Kay*_*Kay 6 .net c# winapi

为什么我用下面的高度和宽度为0:

    static void Main(string[] args)
    {
        Process notePad = new Process();
        notePad.StartInfo.FileName = "notepad.exe";
        notePad.Start();
        IntPtr handle = notePad.Handle;

        RECT windowRect = new RECT();
        GetWindowRect(handle, ref windowRect);
        int width = windowRect.Right - windowRect.Left;
        int height = windowRect.Bottom - windowRect.Top;

        Console.WriteLine("Height: " + height + ", Width: " + width);
        Console.ReadLine();
    }
Run Code Online (Sandbox Code Playgroud)

这是我对GetWindowRect的定义:

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);
Run Code Online (Sandbox Code Playgroud)

这是我对RECT的定义:

    [StructLayout(LayoutKind.Sequential)]
    public struct RECT
    {
        public int Left;        // x position of upper-left corner
        public int Top;         // y position of upper-left corner
        public int Right;       // x position of lower-right corner
        public int Bottom;      // y position of lower-right corner
    }
Run Code Online (Sandbox Code Playgroud)

谢谢大家的帮助.

Dav*_*nan 9

您正在将一个进程句柄传递给一个GetWindowRect需要窗口句柄的函数.当然,这失败了.你应该发送Notepad.MainWindowHandle.

  • @Kay进程句柄与窗口句柄完全不同.只是在.net中,使用你的P/Invoke,你就失去了类型安全性.在普通的win32代码中,当尝试混合进程句柄和窗口句柄时,您会遇到编译器错误. (3认同)

JSB*_*ոգչ 5

在记事本完全启动之前,您可能正在查询大小.试试这个:

    notePad.Start();
    notePad.WaitForInputIdle(); // Waits for notepad to finish startup
    IntPtr handle = notePad.Handle;
Run Code Online (Sandbox Code Playgroud)