调整其他窗口或应用程序的大小c#

时间:2015-08-27 22:25:13

标签: c# windows

我试图用c#将窗口大小调整为1280x720分辨率。我该怎么做?我已尝试在堆叠中发布了大量代码,而我得到的最接近的结果是:

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

感谢您的时间。

2 个答案:

答案 0 :(得分:6)

如果您希望窗口的大小为1280x720,请在MoveWindow调用中使用该大小。

  MoveWindow(handle, Rect.left, Rect.top, 1280, 720, true);

答案 1 :(得分:2)

为响应 David Amaral ,要使窗口居中,请使用:

MoveWindow(handle, (Screen.PrimaryScreen.WorkingArea.Width - 1280) / 2, 
    (Screen.PrimaryScreen.WorkingArea.Height - 720) / 2, 1280, 720, true);

顺便说一句,这里是vb.net中想要的人的代码:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim processes As Process() = Process.GetProcessesByName("notepad")
    For Each p As Process In processes
        Dim handle As IntPtr = p.MainWindowHandle
        Dim Rect As New RECT()
        If GetWindowRect(handle, Rect) Then
            MoveWindow(handle, (My.Computer.Screen.WorkingArea.Width - 1280) \ 2, (My.Computer.Screen.WorkingArea.Height - 720) \ 2, 1280, 720, True)
        End If
    Next
End Sub

<StructLayout(LayoutKind.Sequential)> _
Public Structure RECT
    Public left As Integer
    Public top As Integer
    Public right As Integer
    Public bottom As Integer
End Structure

<DllImport("user32.dll", SetLastError:=True)> _
Private Shared Function GetWindowRect(hWnd As IntPtr, ByRef Rect As RECT) As Boolean
End Function

<DllImport("user32.dll", SetLastError:=True)> _
Private Shared Function MoveWindow(hWnd As IntPtr, X As Integer, Y As Integer, Width As Integer, Height As Integer, Repaint As Boolean) As Boolean
End Function