Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

windows

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.

Process[] processes = Process.GetProcessesByName("notepad");

foreach (Process p in processes)
{

    if (p.MainWindowTitle == title)
    {

        handle = p.MainWindowHandle;

        while ((handle = p.MainWindowHandle) == IntPtr.Zero)
        {
            Thread.Sleep(1000);
            p.Refresh();
        }

        break;
    }

}

Can I make use of handle or p to set the height of the window?

like image 531
Abs Avatar asked Jun 26 '11 14:06

Abs


1 Answers

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.

like image 90
David Heffernan Avatar answered Oct 16 '22 06:10

David Heffernan