Я создал этот класс на основе класса для Windows Forms, который я нашел где-то еще.
Просто добавьте класс в ваш проект WPF и укажите «this» в качестве параметра вспомогательного метода следующим образом:
MessageBoxHelper.PrepToCenterMessageBoxOnForm(this)"
Затем показать окно сообщения:
MessageBox.Show("Hello there!");
/// <summary>
/// This class makes it possible to center a MessageBox over the parent dialog.
/// Usage example:
/// MessageBoxHelper.PrepToCenterMessageBoxOnForm(this);
/// MessageBox.Show("Hello there!);
/// </summary>
public static class MessageBoxHelper
{
public static void PrepToCenterMessageBoxOnForm(Window window)
{
MessageBoxCenterHelper helper = new MessageBoxCenterHelper();
helper.Prep(window);
}
private class MessageBoxCenterHelper
{
private int messageHook;
private IntPtr parentFormHandle;
public void Prep(Window window)
{
NativeMethods.CenterMessageCallBackDelegate callBackDelegate = new NativeMethods.CenterMessageCallBackDelegate(CenterMessageCallBack);
GCHandle.Alloc(callBackDelegate);
parentFormHandle = new WindowInteropHelper(window).Handle;
messageHook = NativeMethods.SetWindowsHookEx(5, callBackDelegate, new IntPtr(NativeMethods.GetWindowLong(parentFormHandle, -6)), NativeMethods.GetCurrentThreadId()).ToInt32();
}
private int CenterMessageCallBack(int message, int wParam, int lParam)
{
NativeMethods.RECT formRect;
NativeMethods.RECT messageBoxRect;
int xPos;
int yPos;
if (message == 5)
{
NativeMethods.GetWindowRect(parentFormHandle, out formRect);
NativeMethods.GetWindowRect(new IntPtr(wParam), out messageBoxRect);
xPos = (int)((formRect.Left + (formRect.Right - formRect.Left) / 2) - ((messageBoxRect.Right - messageBoxRect.Left) / 2));
yPos = (int)((formRect.Top + (formRect.Bottom - formRect.Top) / 2) - ((messageBoxRect.Bottom - messageBoxRect.Top) / 2));
NativeMethods.SetWindowPos(wParam, 0, xPos, yPos, 0, 0, 0x1 | 0x4 | 0x10);
NativeMethods.UnhookWindowsHookEx(messageHook);
}
return 0;
}
}
private static class NativeMethods
{
internal struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
internal delegate int CenterMessageCallBackDelegate(int message, int wParam, int lParam);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool UnhookWindowsHookEx(int hhk);
[DllImport("user32.dll", SetLastError = true)]
internal static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("kernel32.dll")]
internal static extern int GetCurrentThreadId();
[DllImport("user32.dll", SetLastError = true)]
internal static extern IntPtr SetWindowsHookEx(int hook, CenterMessageCallBackDelegate callback, IntPtr hMod, int dwThreadId);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetWindowPos(int hWnd, int hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
}
}