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;

WPF小记-单例窗口、置顶窗口、记录上次关闭位置_第1张图片
//每次打开都是上次窗口的位置
新建一个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();
        }

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

你可能感兴趣的:(wpf)