WPF只允许显示一个子窗体

WPF只允许显示一个子窗体

WPF示例:

private TestFrm objFrm;
private void button_Click(object sender, RoutedEventArgs e)
{
	if (historyFrm == null || historyFrm.IsVisible == false)
    {
        historyFrm = new HistoryFrm();
        historyFrm.Show();
    }
    else if(historyFrm.WindowState == WindowState.Minimized)
    {
        historyFrm.WindowState = WindowState.Normal;
    }
    else
    {
        historyFrm.Activate();
    }
}

WPF子窗体单例模式:

private static TestFrm _instance;
public static TestFrm Instance
{
      get
      {
           if (ReferenceEquals(_instance, null))
           {
                 _instance = new TestFrm();
           }
           return _instance;
       }
}
        

调用:

TestFrm.Instance.Show();

另:
Winform示例:

private TestFrm objFrm;
private void button_Click(object sender, RoutedEventArgs e)
{
	if (objFrm == null || objFrm.IsDisposed)
	{
     	objFrm = new TestFrm();
     	objFrm.Show();
	}
	else
	{
     	objFrm.Activate();
	}
}

另外WPF示例:

WndNavigation _wnd = null;   // WPF窗体全局变量

/// <summary>
/// 适用Show仅打开一个窗体,并显示在相对于主窗体的位置
/// </summary>
private void OpenWnd()
{
    if (_wnd == null || !_wnd.IsLoaded)
    {
        _wnd = new WndNavigation();
        _wnd.Closing += (s, e) => { _wnd = null; };
        _wnd.WindowStartupLocation = WindowStartupLocation.Manual;
        Window owner = System.Windows.Application.Current.MainWindow;
        _wnd.Owner = owner;
        if (owner != null)
        {
            #region 设置本窗体位置
            System.Windows.Point pLeft = owner.PointToScreen(new System.Windows.Point(0, 0));
            IntPtr hwnd = new WindowInteropHelper(owner).Handle;
            HwndSource hwndSource = HwndSource.FromHwnd(hwnd);
            if (hwndSource != null)
                pLeft = hwndSource.CompositionTarget.TransformFromDevice.Transform(pLeft);

            // 在主窗体右上角
            //Point rightTop = new Point(pLeft.X + owner.ActualWidth, pLeft.Y);
            //_wnd.Left = rightTop.X - _wnd.Width - 80;
            //_wnd.Top = rightTop.Y + 25;

            System.Windows.Point rightBottom = new System.Windows.Point(pLeft.X + owner.ActualWidth, pLeft.Y + owner.ActualHeight);

            // 在主窗体右下角
            _wnd.Left = rightBottom.X - _wnd.Width - 110;
            _wnd.Top = rightBottom.Y - _wnd.Height - 70;
            #endregion
        }
        else
        {
            _wnd.Left = SystemParameters.WorkArea.Width - 280;
            _wnd.Top = SystemParameters.WorkArea.Height - 100;
        }
    }

    _wnd.Topmost = true;

    if (!_wnd.IsLoaded)
        _wnd.Show();
    else
        _wnd.Activate();
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值