WPF小记-单例窗口、置顶窗口、记录上次关闭位置

//单例模式窗口

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

}

打开窗口直接Instance.Show()即可

//置顶窗口
此处置顶窗口非一直在桌面上,而是软件关闭后也会跟着关闭,其他情况可一直悬浮置顶在主程序窗口之上

  System.Windows.Interop.WindowInteropHelper mainUI = new System.Windows.Interop.WindowInteropHelper(ViewWindow.Instance);
  mainUI.Owner = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;

放在show之前就好
//每次打开都是上次窗口的位置
新建一个WindowApplicationSettings类,继承ApplicationSettingsBase

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace Export
{
    //此类用来记录每次窗口关闭的位置,为下次打开窗口还是上次的位置
    internal class WindowApplicationSettings: ApplicationSettingsBase
    {
        [UserScopedSettingAttribute()]
        [DefaultSettingValueAttribute("0, 0")]
        public Point WinLocation
        {
             get { return (Point) (this["WinLocation"]); }
             set { this["WinLocation"] = value; }
        }
    }
}

//然后在WPF初始化和loaded中如下改动

public partial class ViewWindow : Window
    {
        WindowApplicationSettings settings = new WindowApplicationSettings();
        public ViewWindow()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(Window_Loaded);
            this.Closing += new CancelEventHandler(Window_Closing);
        }
 		private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            settings.Reload();
            this.Left = settings.WinLocation.X;
            this.Top = settings.WinLocation.Y;
        }
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            settings.WinLocation = new Point(this.Left, this.Top);
            settings.Save();
            e.Cancel = true;  //   
            this.Hide();
        }

这样每次打开都是上次关闭时的位置了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值