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

5

我想使用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);
            }
        }
    }
}

感谢您的时间。

1
你应该使用Rect.top而不是Rect.right,这就是为什么窗口有时会移出屏幕的原因。 - LarsTech
感谢您的时间,非常感激。 - David Amaral
2个回答

7
如果你想让窗口的大小为1280x720,则在MoveWindow调用中使用该大小。
  MoveWindow(handle, Rect.left, Rect.top, 1280, 720, true);

1
更新了我的答案,你想让窗口不动,需要将左和上的参数传递给MoveWindow函数。 - shf301
1
很酷。但是我如何在调整大小后将它居中显示在屏幕上? - David Amaral
感谢您的时间,非常感激。 - David Amaral
那段代码无法运行。它显示未识别的转义序列 ""。 - David Amaral
尝试使用“/”进行操作。在vb.net中,“\”运算符用于返回整数结果,而不是浮点结果,但在c#中不存在。 - Drarig29
显示剩余3条评论

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接