一、弹窗示例
1、自定义弹窗
前台
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock x:Name="tbox" HorizontalAlignment="Center"
VerticalAlignment="Center" FontWeight="Bold" />
<UniformGrid Grid.Row="1" Columns="2">
<Button Width="100" Height="NaN"
Margin="10" Padding="3"
HorizontalAlignment="Center"
Click="Button_OK_Click" Content="OK"
FontSize="16" />
<Button Width="100" Height="NaN"
Margin="10" Padding="3"
HorizontalAlignment="Center"
Click="Button_Cancel_Click" Content="Cancel"
FontSize="16" />
</UniformGrid>
</Grid>
后台
public partial class TestDialog : Window
{
public TestDialog(string message)
{
InitializeComponent();
tbox.Text = message;
}
private void Button_OK_Click(object sender, RoutedEventArgs e)
{
DialogResult = true;
Close();
}
private void Button_Cancel_Click(object sender, RoutedEventArgs e)
{
DialogResult = false;
Close();
}
}
2、DialogHelper
public class DialogHelper
{
//从Handle中获取Window对象
static Window GetWindowFromHwnd(IntPtr hwnd)
{
return (Window)HwndSource.FromHwnd(hwnd).RootVisual;
}
//GetForegroundWindow API
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
//调用GetForegroundWindow然后调用GetWindowFromHwnd
static Window GetTopWindow()
{
var hwnd = GetForegroundWindow();
if (hwnd == null)
return null;
return GetWindowFromHwnd(hwnd);
}
//显示对话框并自动设置Owner,可以理解为子窗体添加父窗体
public static void ShowDialog(Window win)
{
win.Owner = GetTopWindow();
win.ShowInTaskbar = false; //false表示不显示新的窗口,默认当前打开窗口为一个子窗口(不会显示两个窗口)
win.ShowDialog();
}
}
3、使用
DialogHelper.ShowDialog(new TestDialog("Test Dialog Show"));