From cfffbdb2d57f07f95de3a6f47e430c888664faad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9E=AB=E9=9B=A8?= <737345039@qq.com> Date: Sun, 22 Jan 2023 00:58:43 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20WPF=E7=9A=84MessageBox=E7=9B=B8?= =?UTF-8?q?=E5=AF=B9=E4=B8=BB=E7=95=8C=E9=9D=A2=E5=B1=85=E4=B8=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 参考链接:https://stackoverflow.com/questions/1732443 --- src/MaaWpfGui/Helper/MessageBoxManager.cs | 44 +++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/src/MaaWpfGui/Helper/MessageBoxManager.cs b/src/MaaWpfGui/Helper/MessageBoxManager.cs index 43212be7bc..1b53577aa8 100644 --- a/src/MaaWpfGui/Helper/MessageBoxManager.cs +++ b/src/MaaWpfGui/Helper/MessageBoxManager.cs @@ -14,9 +14,11 @@ #pragma warning disable SA1307 #pragma warning disable SA1401 #pragma warning disable IDE0051 +using System.Drawing; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Text; +using System.Windows.Interop; [assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true)] @@ -45,6 +47,12 @@ namespace System.Windows.Forms private const int MBYes = 6; private const int MBNo = 7; + [DllImport("user32.dll")] + private static extern bool GetWindowRect(IntPtr hWnd, ref Rectangle lpRect); + + [DllImport("user32.dll")] + private static extern int MoveWindow(IntPtr hWnd, int x, int y, int nWidth, int nHeight, bool bRepaint); + [DllImport("user32.dll")] private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam); @@ -200,11 +208,47 @@ namespace System.Windows.Forms } } } + + source = CreateHwndSource(Windows.Application.Current.MainWindow); + if (source != null) + { + CenterWindow(msg.hwnd); + } } return CallNextHookEx(hook, nCode, wParam, lParam); } + private static HwndSource source = null; + + private static HwndSource CreateHwndSource(Window owner) + { + return (HwndSource)PresentationSource.FromVisual(owner); + } + + private static void CenterWindow(IntPtr hChildWnd) + { + Rectangle recChild = new Rectangle(0, 0, 0, 0); + bool success = GetWindowRect(hChildWnd, ref recChild); + + int width = recChild.Width - recChild.X; + int height = recChild.Height - recChild.Y; + + Rectangle recParent = new Rectangle(0, 0, 0, 0); + success = GetWindowRect(source.Handle, ref recParent); + + Point ptCenter = new Point(0, 0); + ptCenter.X = recParent.X + ((recParent.Width - recParent.X) / 2); + ptCenter.Y = recParent.Y + ((recParent.Height - recParent.Y) / 2); + + Point ptStart = new Point(0, 0); + ptStart.X = ptCenter.X - (width / 2); + ptStart.Y = ptCenter.Y - (height / 2); + + int result = MoveWindow(hChildWnd, Convert.ToInt32(ptStart.X), Convert.ToInt32(ptStart.Y), + width, height, false); + } + private static bool MessageBoxEnumProc(IntPtr hWnd, IntPtr lParam) { StringBuilder className = new StringBuilder(10);