主窗口居中置顶
public MainWindow()
{
InitializeComponent();
WindowStartupLocation = WindowStartupLocation.CenterScreen;
this.Topmost = true;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
IntPtr hwnd = new WindowInteropHelper(this).Handle;
TopMostTool.SetTopmost(hwnd);
}
using System;
using System.Runtime.InteropServices;
/// <summary>
/// 置顶帮助类
/// </summary>
public class TopMostTool
{
/// <summary>
/// 窗体置顶
/// </summary>
/// <param name="windowName">需要置顶的窗体的名字 Title</param>
public static void SetTopWindow(string windowName)
{
IntPtr frm = Win32ApiHelper.FindWindow(null, windowName); // 程序中需要置顶的窗体的名字
if (frm != IntPtr.Zero)
{
Win32ApiHelper.SetWindowPos(frm, (IntPtr)Win32ApiHelper.HWND_TOPMOST, 0, 0, 0, 0, (int)Win32ApiHelper.WindowFlags.SWP_NOMOVE | (int)Win32ApiHelper.WindowFlags.SWP_NOSIZE);
var child = Win32ApiHelper.FindWindowEx(frm, IntPtr.Zero, null, windowName);
}
}
/// <summary>
/// 窗体置顶
/// </summary>
/// <param name="handle">窗体句柄</param>
public static void SetTopmost(IntPtr handle)
{
Win32ApiHelper.SetWindowPos(handle, (IntPtr)Win32ApiHelper.HWND_TOPMOST, 0, 0, 0, 0, (int)Win32ApiHelper.WindowFlags.SWP_NOMOVE | (int)Win32ApiHelper.WindowFlags.SWP_NOSIZE);
}
}
子窗口居中显示
var dlg = new ChildDlg()
{
Background = Brushes.Black,
Opacity = 0.8,
AllowsTransparency = true,
WindowStyle = WindowStyle.None,
WindowState = WindowState.Normal,
Topmost = true,
WindowStartupLocation = WindowStartupLocation.CenterOwner,
Owner = mainWindow,
Width = mainWindow.Width,
Height = mainWindow.Height,
};
dlg.ShowDialog();