How to set the height of a window using c#?

后端 未结 2 1066
我寻月下人不归
我寻月下人不归 2020-12-16 00:05

Is it possible to set the height of a window using the window handle or process handle?

I have the following so far, assume the application in question is notepad.

2条回答
  •  一整个雨季
    2020-12-16 00:57

    This is how I would do it:

    using System;
    using System.Diagnostics;
    using System.Runtime.InteropServices;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            [StructLayout(LayoutKind.Sequential)]
            public struct RECT
            {
                public int left;
                public int top;
                public int right;
                public int bottom;
            }
    
            [DllImport("user32.dll", SetLastError = true)]
            static extern bool GetWindowRect(IntPtr hWnd, ref RECT Rect);
    
            [DllImport("user32.dll", SetLastError = true)]
            static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int Width, int Height, bool Repaint);
    
            static void Main(string[] args)
            {
                Process[] processes = Process.GetProcessesByName("notepad");
                foreach (Process p in processes)
                {
                    IntPtr handle = p.MainWindowHandle;
                    RECT Rect = new RECT();
                    if (GetWindowRect(handle, ref Rect))
                        MoveWindow(handle, Rect.left, Rect.right, Rect.right-Rect.left, Rect.bottom-Rect.top + 50, true);
                }
            }
        }
    }
    

    While you can do it with SetWindowPos, and SetWindowPos is the newer and more capable API, MoveWindow is just easier to call.

提交回复
热议问题