using Prism.Regions;
using System.Collections.Generic;
using System.Windows;
using Venus_Themes.CustomControls;
using Venus_Unity;
using System.Linq;
using System;
using Venus_MainPages.Views;
using System.Windows.Controls;
using System.Windows.Media;
using Venus_Core;
using System.Reflection;
using Venus_MainPages.Unity;
using MECF.Framework.Common.DataCenter;
using MECF.Framework.Common.OperationCenter;
using Venus_MainPages.ViewModels;
using MECF.Framework.Common.CommonData;
using System.Windows.Threading;
using Venus_Themes.Unity;
using MECF.Framework.Common.Equipment;
using WinInterop = System.Windows.Interop;
using System.Runtime.InteropServices;
using System.IO;
using System.Windows.Media.Imaging;
using Venus_MainPages.Roles;
using WPF.Themes.UserControls;
namespace Venus_UI.Views
{
    /// 
    /// ShellView.xaml 的交互逻辑
    /// 
    public partial class ShellView : Window
    {
        IRegionManager m_regionManager;
        IRegionNavigationService m_regionNavigationService;
        //List VenusMenu;
        List RoleDefines;
        public List centerTabViews = new List();
        public List buttonList = new List();
        DispatcherTimer timer = new DispatcherTimer();
        User CurrentUser = new User("admin", "admin", Role.Manager);
        //public DateTime Time
        //{ 
        //get { return DateTime.Now; }
        //}
        public static readonly DependencyProperty TimeProperty = DependencyProperty.Register(
           "Time", typeof(DateTime), typeof(ShellView));
        public DateTime Time
        {
            get { return (DateTime)this.GetValue(TimeProperty); }
            set { this.SetValue(TimeProperty, value); }
        }
        public ShellView(IRegionManager regionManager, IRegionNavigationService regionNavigationService)
        {
            InitializeComponent();
            LoginView loginView = new LoginView();
            loginView.ShowDialog();
            CurrentUser = loginView.CurrentUser;
            if (!loginView.IsLoginSuccess)
            {
               this.Close();
            }
            m_regionManager = regionManager;
            m_regionNavigationService = regionNavigationService;
            m_regionManager.RegisterViewWithRegion("TopRegion", typeof(Venus_MainPages.Views.TopView));
            VenusGlobalEvents.SlotRightClickChangedEvent += Instance_SlotRightClickChangedEvent;
            VenusGlobalEvents.SlotWaferTransferEvent += Instance_SlotStartTransferEvent;
            timer.Tick += timer_Tick;
            timer.Interval = TimeSpan.FromSeconds(0.5);
            timer.Start();
            UIEvents.PMDoorRaiseChangedEvent += UIEvents_PMDoorRaiseChangedEvent;
            UIEvents.LLTDoorRaiseChangedEvent += UIEvents_LLTDoorRaiseChangedEvent;
            UIEvents.LLEDoorRaiseChangedEvent += UIEvents_LLEDoorRaiseChangedEvent;
            UIEvents.ChamberCreateDeleteWaferEvent += UIEvents_ChamberCreateDeleteWaferEvent;
            UIEvents.InitRaiseChangedEvent += UIEvents_InitRaiseChangedEvent;
            UIEvents.IncludeRaiseChangedEvent += UIEvents_IncludeRaiseChangedEvent;
            UIEvents.OnlineRaiseChangedEvent += UIEvents_OnlineRaiseChangedEvent;
            this.SourceInitialized += (o, e) =>
            {
                System.IntPtr handler = (new WinInterop.WindowInteropHelper(this)).Handle;
                WinInterop.HwndSource.FromHwnd(handler).AddHook(new WinInterop.HwndSourceHook(WindowProc));
            };
            this.MaxHeight = SystemParameters.WorkArea.Height;
            ResizeMode = ResizeMode.CanMinimize;
            this.WindowState = this.WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;
        }
       
        public ShellView()
        { 
        
        }
        void timer_Tick(object sender, EventArgs e)
        {
            if (Anychange.needchange)
            {
                Anystationchange(Anychange.menuname, Anychange.args);
                Anychange.needchange = false;
            }
            Tag=DateTime.Now;
        }
        private void Instance_SlotRightClickChangedEvent(OpenSEMI.Ctrlib.Controls.Slot slot)
        {
            if (slot != null)
            {
                ContextMenu cm = ContextMenuManager.Instance.GetSlotMenus(slot);
                if (cm != null)
                {
                    slot.ContextMenu = cm;
                }
                return;
            }
        }
        private void Instance_SlotStartTransferEvent(OpenSEMI.Ctrlib.Controls.DragDropEventArgs e)
        {
            string info = " from " + e.TranferFrom.ModuleID + " slot " + (e.TranferFrom.SlotID + 1).ToString() + " to " + e.TranferTo.ModuleID + " slot " + (e.TranferTo.SlotID + 1).ToString();
            string message = "Are you sure to transfer the wafer: \n" + info;
            WaferDialogViewModel vm = new WaferDialogViewModel();
            vm.ConfirmText = message;
            WaferDialogView dialog = new WaferDialogView()
            {
                Owner = Application.Current.MainWindow,
            };
            dialog.DataContext = vm;
            dialog.Height = 300;
            dialog.Width = 400;
            bool alignflag = false;
            bool coolingflag = false;
            double angel = 0;
            double coolingtime = 0;
            if (dialog.ShowDialog() == true)
            {
                alignflag = (bool)dialog.AlignFlag;
                coolingflag = (bool)dialog.CoolingFlag;
                if (alignflag && !string.IsNullOrEmpty(dialog.Angle))
                {
                    angel = Convert.ToDouble(dialog.Angle);
                }
                if (coolingflag && !string.IsNullOrEmpty(dialog.CoolingTime))
                {
                    coolingtime = Convert.ToDouble(dialog.CoolingTime);
                }
                //from robot to robot is illegal. Must be stop
                if (e.TranferFrom.ModuleID == e.TranferTo.ModuleID && (e.TranferTo.ModuleID == ModuleName.EfemRobot.ToString() || e.TranferTo.ModuleID == ModuleName.TMRobot.ToString()))
                {
                }
                else
					if(e.TranferTo.ModuleID == "VPA" || string.IsNullOrEmpty(e.TranferTo.ModuleID))
                    InvokeClient.Instance.Service.DoOperation("System.MoveWafer",
                        e.TranferFrom.ModuleID, e.TranferFrom.SlotID, "VPA", 0, true, 0, coolingflag, coolingtime, "");
                
                    InvokeClient.Instance.Service.DoOperation("System.MoveWafer",
                        e.TranferFrom.ModuleID, e.TranferFrom.SlotID, e.TranferTo.ModuleID, e.TranferTo.SlotID, alignflag, angel, coolingflag, coolingtime, "");
            }
            else
            {
                ModuleManager.OnFlashWafer(new FlashWaferInformation() { ModuleName = e.TranferFrom.ModuleID, SoltId = e.TranferFrom.SlotID });
                //ModuleManager.OnFlashWafer(new FlashWaferInformation() { ModuleName = e.TranferTo.ModuleID, SoltId = e.TranferTo.SlotID });
            }
            e.TranferFrom.ClearDragDropStatus();
            e.TranferTo.ClearDragDropStatus();
        }
        private void CustomWnd_Loaded(object sender, RoutedEventArgs e)
        {
            var h1 = SystemParameters.WorkArea.Height;
            var h2 = SystemParameters.PrimaryScreenHeight;
            //this.ResizeMode = ResizeMode.CanResize;
            //System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width / SystemParameters.PrimaryScreenWidth
            //VenusMenu = SerializeHelper.Instance.ReadFromJsonFile>($"Config/UIMenu.json");
            //App.currentUser
            string configPath = "";
            string uiConfig = "";
            object obj2 = QueryDataClient.Instance.Service.GetData("System.ConfigType");
            var configType = (ConfigType)Convert.ToInt32(obj2);
            if (configType == ConfigType.Other || configType == ConfigType.Kepler2300 || configType == ConfigType.Kepler2200)
            {
                uiConfig = "_Kepler";
            }
            else if (configType == ConfigType.VenusSE || configType == ConfigType.VenusDE)
            {
                uiConfig = "_VenusSE";
            }
            //else if (configType == ConfigType.Venus)
            //{
            //    uiConfig = "_Venus";
            //}
            if (File.Exists($"Config/UIMenu{uiConfig}.json"))
            {
                configPath = $"Config/UIMenu{uiConfig}.json";
            }
            else if (File.Exists($"Config/Menu{uiConfig}.json"))
            {
                configPath = $"Config/Menu{uiConfig}.json";
            }
            else
            {
                WPFMessageBox.ShowError("未发现UI Config配置文件,退出UI");
                this.Close();
            }
            RoleDefines = SerializeHelper.Instance.ReadFromJsonFile>(configPath);
            string[] allModules = QueryDataClient.Instance.Service.GetConfig($"System.InstalledModules").ToString().Split(',');
            //TabControl tabControl = new TabControl();
            int role = (int)CurrentUser.Role;
            var menu = RoleDefines[role].Menus;
            List modules = new List();
            for (int i = 0; i < menu.Count; i++)
            {
                if (!modules.Contains(menu[i].FirstMenu))
                {
                    modules.Add(menu[i].FirstMenu);
                    centerTabViews.Add(new TabControl());
                }
            }
            int index = -1;
            string lastModule="";
            
            for (int i = 0; i < menu.Count; i++)
            {
                if (menu[i].Permission == MenuPermission.None)
                {
                    continue;
                }
                if (menu[i].FirstMenu == "PMA" || menu[i].FirstMenu == "PMB" || menu[i].FirstMenu == "PMC" || menu[i].FirstMenu == "PMD" || menu[i].FirstMenu == "TM")
                {
                    if (!allModules.Contains(menu[i].FirstMenu))
                    {
                        continue;
                    }
                }
                string className;
                if ((menu[i].FirstMenu == "PMA" || menu[i].FirstMenu == "PMB" || menu[i].FirstMenu == "PMC" || menu[i].FirstMenu == "PMD") && menu[i].SecondMenu=="Operation")
                {
                    JetChamber jetChamber = (JetChamber)(Convert.ToInt32(QueryDataClient.Instance.Service.GetConfig($"{menu[i].FirstMenu}.ChamberType")));
                    className = $"Venus_MainPages.Views.Over{jetChamber.ToString()}View";
                }
                else
                {
                    className = $"Venus_MainPages.Views.{menu[i].View}";
                }
                Type t = Type.GetType($"{className},Venus_MainPages");
                var obj = System.Activator.CreateInstance(t);
                if (menu[i].FirstMenu == "PMA" || menu[i].FirstMenu == "PMB" || menu[i].FirstMenu == "PMC" || menu[i].FirstMenu == "PMD")
                {
                    MethodInfo methodInfo = t.GetMethod("Init", new Type[] { typeof(string) });
                    methodInfo?.Invoke(obj, new object[] { menu[i].FirstMenu });
                }
                else if (menu[i].SecondMenu == "TM IO")
                {
                    MethodInfo methodInfo = t.GetMethod("Init", new Type[] { typeof(string) });
                    methodInfo?.Invoke(obj, new object[] { "TM"});
                }
                else if (menu[i].FirstMenu == "Operation" && menu[i].SecondMenu == "IO")
                {
                    MethodInfo methodInfo = t.GetMethod("Init", new Type[] { typeof(string) });
                    methodInfo?.Invoke(obj, new object[] { "SETM" });
                }
                else if (menu[i].FirstMenu == "Operation" && menu[i].SecondMenu == "IO1")
                {
                    MethodInfo methodInfo = t.GetMethod("Init", new Type[] { typeof(string) });
                    methodInfo?.Invoke(obj, new object[] { "DETM" });
                }
                if (lastModule != menu[i].FirstMenu)
                {
                    AduRadioButtonIcon aduRadioButtonIcon = new AduRadioButtonIcon();
                    index += 1;
                    if (index == 0)
                    {
                        aduRadioButtonIcon.IsChecked = true;
                    }
                    //IconElement.SetPathData(aduRadioButtonIcon, (Geometry)aduRadioButtonIcon.FindResource($"Icon_{menu[i].se}"));
                    aduRadioButtonIcon.Content = menu[i].FirstMenu;
                    aduRadioButtonIcon.Checked += AduRadioButtonIcon_Click;
                    aduRadioButtonIcon.SelectBackground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#0076C4"));
                    aduRadioButtonIcon.SelectColor = new SolidColorBrush((Colors.White));
                    aduRadioButtonIcon.Width = 180;
                    aduRadioButtonIcon.Tag = index;
                    buttonList.Add(aduRadioButtonIcon);
                    Bottom_Frame.Children.Add(aduRadioButtonIcon);
                }
                TabItem tabItem = new TabItem() { Header = menu[i].SecondMenu, Content = obj };
                
                if (menu[i].Permission == MenuPermission.ReadOnly)
                {
                    (tabItem.Content as Control).IsEnabled = false;
                }
                centerTabViews[index].Items.Add(tabItem);
                (tabItem.Content as Control).IsVisibleChanged += TabItem_IsVisibleChanged;
                lastModule = menu[i].FirstMenu;
            }
            Main_Frame.Content = centerTabViews[0];
            ModuleManager.Initialize();
        }
        private void TabItem_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            var viewmodel = (sender as Control).DataContext;
            Type t = viewmodel.GetType();
            MethodInfo methodInfo = t.GetMethod("EnterExitView", new Type[] { typeof(bool) });
            methodInfo?.Invoke(viewmodel, new object[] { e.NewValue });
        }
        public void Anystationchange(string menuviewItem, WaferHistoryWafer queryFilter)
        {
            UserControl address = new ProcessHistoryView();
            ProcessHistoryViewModel vm = new ProcessHistoryViewModel() { };
            vm.searchlot(queryFilter.WaferGuid);
            //vm.OnDataGridSelectionChanged(vm.Recipes[0]);
            address.DataContext = vm;
            int s = 0;
            for (int i = 0; i < centerTabViews.Count; i++)
            {
                var item = centerTabViews[i];
                foreach (TabItem v in item.Items)
                {
                    if (v.Header.ToString() == "Process History")
                    {
                        s = i;
                    }
                }
            }
            if (s != 0)
            {
                centerTabViews[s].Items[2] = new TabItem() { Header = menuviewItem, Content = address };
                centerTabViews[s].SelectedIndex = 2;
                Main_Frame.Content = centerTabViews[s];
            }
        }
        private void AduRadioButtonIcon_Click(object sender, RoutedEventArgs e)
        {
            var currentButton = sender as AduRadioButtonIcon;
            Main_Frame.Content = centerTabViews[Convert.ToInt32(currentButton.Tag)];
        }
        private void CustomWnd_Closed(object sender, EventArgs e)
        {
            System.Diagnostics.Process.GetCurrentProcess().Kill();
        }
        private void UIEvents_ChamberCreateDeleteWaferEvent(WaferOperation obj)
        {
            if (obj.IsCreate == true)
            {
                InvokeClient.Instance.Service.DoOperation("CreateWafer", obj.ModuleName, 0);
            }
            else
            {
                InvokeClient.Instance.Service.DoOperation("DeleteWafer", obj.ModuleName, 0);
            }
        }
        private void UIEvents_PMDoorRaiseChangedEvent(DoorPara obj)
        {
            //var value = SC.GetValue($"{obj?.ModuleName}.ChamberType");
            //var value=(JetChamber)Enum.Parse(typeof(JetChamber), QueryDataClient.Instance.Service.GetConfig($"{obj?.ModuleName}.ChamberType").ToString());
            JetChamber jetChamber = (JetChamber)Enum.Parse(typeof(JetChamber), QueryDataClient.Instance.Service.GetConfig($"{obj?.ModuleName}.ChamberType").ToString());
            if (jetChamber == JetChamber.VenusDE)
            {
                InvokeClient.Instance.Service.DoOperation($"{obj?.ModuleName}.SetLinerDoor", obj.IsOpen == "Open" ? true : false);
            }
            else
            {
                InvokeClient.Instance.Service.DoOperation($"TM.SetMFSlitDoor", obj.ModuleName, obj.IsOpen == "Open" ? true : false);
            }
            //InvokeClient.Instance.Service.DoOperation($"{obj?.ModuleName}.SlitDoor.{obj?.IsOpen}");
        }
        private void UIEvents_LLTDoorRaiseChangedEvent(DoorPara obj)
        {
            InvokeClient.Instance.Service.DoOperation($"TM.SetMFSlitDoor", obj.ModuleName, obj.IsOpen == "Open" ? true : false);
        }
        private void UIEvents_LLEDoorRaiseChangedEvent(DoorPara obj)
        {
            InvokeClient.Instance.Service.DoOperation($"TM.SetEFEMSlitDoor", obj.ModuleName, obj.IsOpen == "Open" ? true : false);
        }
        private void UIEvents_InitRaiseChangedEvent(string obj)
        {
            InvokeClient.Instance.Service.DoOperation($"{obj}.Home");
        }
        private void UIEvents_IncludeRaiseChangedEvent(IncludePara obj)
        {
            if (obj.IsInclude)
            {
                InvokeClient.Instance.Service.DoOperation($"{obj.ModuleName}.{RtOperation.Include}");
            }
            else
            { 
                InvokeClient.Instance.Service.DoOperation($"{obj.ModuleName}.{RtOperation.Exclude}");
            }
        }
        private void UIEvents_OnlineRaiseChangedEvent(IncludePara obj)
        {
            if (obj.ModuleName == "EFEM")
            {
                InvokeClient.Instance.Service.DoOperation($"{obj.ModuleName}.{RtOperation.Online}", obj.IsInclude);
            }
            else if (obj.ModuleName == "System")
            {
                if (obj.IsInclude)
                {
                    InvokeClient.Instance.Service.DoOperation("System.SetAutoMode");
                }
                else
                {
                    InvokeClient.Instance.Service.DoOperation("System.SetManualMode");
                }
            }
            else
            {
                if (obj.IsInclude)
                {
                    InvokeClient.Instance.Service.DoOperation($"{obj.ModuleName}.{RtOperation.Online}");
                }
                else
                {
                    InvokeClient.Instance.Service.DoOperation($"{obj.ModuleName}.{RtOperation.Offline}");
                }
            }
           
        }
        #region 调用api功能部分
        void win_SourceInitialized(object sender, EventArgs e)
        {
            System.IntPtr handle = (new WinInterop.WindowInteropHelper(this)).Handle;
            WinInterop.HwndSource.FromHwnd(handle).AddHook(new WinInterop.HwndSourceHook(WindowProc));
        }
        private static System.IntPtr WindowProc(
              System.IntPtr hwnd,
              int msg,
              System.IntPtr wParam,
              System.IntPtr lParam,
              ref bool handled)
        {
            switch (msg)
            {
                case 0x0024:
                    WmGetMinMaxInfo(hwnd, lParam);
                    handled = true;
                    break;
            }
            return (System.IntPtr)0;
        }
        private static void WmGetMinMaxInfo(System.IntPtr hwnd, System.IntPtr lParam)
        {
            MINMAXINFO mmi = (MINMAXINFO)Marshal.PtrToStructure(lParam, typeof(MINMAXINFO));
            // Adjust the maximized size and position to fit the work area of the correct monitor
            int MONITOR_DEFAULTTONEAREST = 0x00000002;
            System.IntPtr monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
            if (monitor != System.IntPtr.Zero)
            {
                MONITORINFO monitorInfo = new MONITORINFO();
                GetMonitorInfo(monitor, monitorInfo);
                RECT rcWorkArea = monitorInfo.rcWork;
                RECT rcMonitorArea = monitorInfo.rcMonitor;
                mmi.ptMaxPosition.x = Math.Abs(rcWorkArea.left - rcMonitorArea.left);
                mmi.ptMaxPosition.y = Math.Abs(rcWorkArea.top - rcMonitorArea.top);
                mmi.ptMaxSize.x = Math.Abs(rcWorkArea.right - rcWorkArea.left);
                mmi.ptMaxSize.y = Math.Abs(rcWorkArea.bottom - rcWorkArea.top);
            }
            Marshal.StructureToPtr(mmi, lParam, true);
        }
        /// 
        /// POINT aka POINTAPI
        /// 
        [StructLayout(LayoutKind.Sequential)]
        public struct POINT
        {
            /// 
            /// x coordinate of point.
            /// 
            public int x;
            /// 
            /// y coordinate of point.
            /// 
            public int y;
            /// 
            /// Construct a point of coordinates (x,y).
            /// 
            public POINT(int x, int y)
            {
                this.x = x;
                this.y = y;
            }
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct MINMAXINFO
        {
            public POINT ptReserved;
            public POINT ptMaxSize;
            public POINT ptMaxPosition;
            public POINT ptMinTrackSize;
            public POINT ptMaxTrackSize;
        };
        /// 
        /// 
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public class MONITORINFO
        {
            /// 
            ///             
            public int cbSize = Marshal.SizeOf(typeof(MONITORINFO));
            /// 
            ///             
            public RECT rcMonitor = new RECT();
            /// 
            ///             
            public RECT rcWork = new RECT();
            /// 
            ///             
            public int dwFlags = 0;
        }
        ///  Win32 
        [StructLayout(LayoutKind.Sequential, Pack = 0)]
        public struct RECT
        {
            ///  Win32 
            public int left;
            ///  Win32 
            public int top;
            ///  Win32 
            public int right;
            ///  Win32 
            public int bottom;
            ///  Win32 
            public static readonly RECT Empty = new RECT();
            ///  Win32 
            public int Width
            {
                get { return Math.Abs(right - left); }  // Abs needed for BIDI OS
            }
            ///  Win32 
            public int Height
            {
                get { return bottom - top; }
            }
            ///  Win32 
            public RECT(int left, int top, int right, int bottom)
            {
                this.left = left;
                this.top = top;
                this.right = right;
                this.bottom = bottom;
            }
            ///  Win32 
            public RECT(RECT rcSrc)
            {
                this.left = rcSrc.left;
                this.top = rcSrc.top;
                this.right = rcSrc.right;
                this.bottom = rcSrc.bottom;
            }
            ///  Win32 
            public bool IsEmpty
            {
                get
                {
                    // BUGBUG : On Bidi OS (hebrew arabic) left > right
                    return left >= right || top >= bottom;
                }
            }
            ///  Return a user friendly representation of this struct 
            public override string ToString()
            {
                if (this == RECT.Empty) { return "RECT {Empty}"; }
                return "RECT { left : " + left + " / top : " + top + " / right : " + right + " / bottom : " + bottom + " }";
            }
            ///  Determine if 2 RECT are equal (deep compare) 
            public override bool Equals(object obj)
            {
                if (!(obj is Rect)) { return false; }
                return (this == (RECT)obj);
            }
            /// Return the HashCode for this struct (not garanteed to be unique)
            public override int GetHashCode()
            {
                return left.GetHashCode() + top.GetHashCode() + right.GetHashCode() + bottom.GetHashCode();
            }
            ///  Determine if 2 RECT are equal (deep compare)
            public static bool operator ==(RECT rect1, RECT rect2)
            {
                return (rect1.left == rect2.left && rect1.top == rect2.top && rect1.right == rect2.right && rect1.bottom == rect2.bottom);
            }
            ///  Determine if 2 RECT are different(deep compare)
            public static bool operator !=(RECT rect1, RECT rect2)
            {
                return !(rect1 == rect2);
            }
        }
        [DllImport("user32")]
        internal static extern bool GetMonitorInfo(IntPtr hMonitor, MONITORINFO lpmi);
        /// 
        /// 
        /// 
        [DllImport("User32")]
        internal static extern IntPtr MonitorFromWindow(IntPtr handle, int flags);
        #endregion
        #region 截屏
        private void SaveWindowContent(Window source, string fileName)
        {
            //FrameworkElement elem = source.Content as FrameworkElement;
            RenderTargetBitmap targetBitmap = new RenderTargetBitmap(
                                       960,
                                       490,
                                       48d,
                                       48d,
                                       PixelFormats.Default);
            targetBitmap.Render(source);
            BmpBitmapEncoder encoder = new BmpBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(targetBitmap));
            // save file to disk
            using (FileStream fs = File.Open(fileName, FileMode.OpenOrCreate))
            {
                encoder.Save(fs);
            }
        }
        #endregion
        private   void Window_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            //this.buttonList[1].IsChecked = true;
            //await System.Threading.Tasks.Task.Delay(10);
            //SaveWindowContent(this, "test.jpg");
            //this.buttonList[0].IsChecked = true;
        }      
    }
}