add restart with windows and autorestart

This commit is contained in:
thuannd88
2024-09-06 23:23:19 +07:00
parent bcfef9d82d
commit 84d9f15ab7
10 changed files with 306 additions and 24 deletions
+12
View File
@@ -4,9 +4,21 @@
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:SafeBagDE70.Admin" xmlns:local="clr-namespace:SafeBagDE70.Admin"
xmlns:hc="https://handyorg.github.io/handycontrol"
mc:Ignorable="d" mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"> d:DesignHeight="450" d:DesignWidth="800">
<Grid> <Grid>
<hc:SimpleStackPanel HorizontalAlignment="Left" VerticalAlignment="Top">
<CheckBox x:Name="cbStartWithWindows" Content="Khởi động cùng Windows" Checked="cbStartWithWindows_Checked" Unchecked="cbStartWithWindows_Unchecked"/>
<Separator/>
<TextBlock Text="Thời gian khởi động lại"/>
<hc:TimePicker x:Name="timePicker" SelectedTimeChanged="timePicker_SelectedTimeChanged" Style="{StaticResource TimePickerPlus}">
<hc:TimePicker.Clock>
<hc:ListClock/>
</hc:TimePicker.Clock>
</hc:TimePicker>
</hc:SimpleStackPanel>
</Grid> </Grid>
</UserControl> </UserControl>
+154 -1
View File
@@ -1,6 +1,12 @@
using System; using HandyControl.Controls;
using Microsoft.Win32;
using SafeBagDE70.API;
using Serilog;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Reflection;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows; using System.Windows;
@@ -12,6 +18,7 @@ using System.Windows.Media;
using System.Windows.Media.Imaging; using System.Windows.Media.Imaging;
using System.Windows.Navigation; using System.Windows.Navigation;
using System.Windows.Shapes; using System.Windows.Shapes;
using System.Windows.Threading;
namespace SafeBagDE70.Admin namespace SafeBagDE70.Admin
{ {
@@ -20,9 +27,155 @@ namespace SafeBagDE70.Admin
/// </summary> /// </summary>
public partial class AdminSettingsUC : UserControl public partial class AdminSettingsUC : UserControl
{ {
string appName = "";
public AdminSettingsUC() public AdminSettingsUC()
{ {
InitializeComponent(); InitializeComponent();
LoadStartupSetting();
timePicker.SelectedTime = Properties.Settings.Default.RestartTime;
SetupAutoRestart();
}
private void LoadStartupSetting()
{
// Open the registry key for the current user's startup applications
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", false);
appName = Assembly.GetEntryAssembly()?.GetName().Name;
if (key != null)
{
// Check if the app is already set to start with Windows
string value = key.GetValue(appName) as string;
// If the app is listed in the startup items, set the checkbox to checked
cbStartWithWindows.IsChecked = value != null;
}
}
private void cbStartWithWindows_Checked(object sender, RoutedEventArgs e)
{
// Add the app to startup when the checkbox is checked
AddApplicationToStartup();
}
private void cbStartWithWindows_Unchecked(object sender, RoutedEventArgs e)
{
// Remove the app from startup when the checkbox is unchecked
RemoveApplicationFromStartup();
}
private void AddApplicationToStartup()
{
// Get the path to the executable
string exePath = Process.GetCurrentProcess().MainModule.FileName;
// Open the registry key for the current user's startup applications
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
if (key != null)
{
// Add the application to the startup list
key.SetValue(appName, exePath);
}
}
private void RemoveApplicationFromStartup()
{
// Open the registry key for the current user's startup applications
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
if (key != null)
{
// Remove the application from the startup list
key.DeleteValue(appName, false);
}
}
private void timePicker_SelectedTimeChanged(object sender, HandyControl.Data.FunctionEventArgs<DateTime?> e)
{
if(timePicker.SelectedTime!= Properties.Settings.Default.RestartTime)
{
Properties.Settings.Default.RestartTime = timePicker.SelectedTime == null ? DateTime.Today.AddHours(2) : (DateTime)timePicker.SelectedTime;
Properties.Settings.Default.Save();
SetupAutoRestart();
}
}
private DispatcherTimer timer;
private DispatcherTimer checkFlagTimer;
private void SetupAutoRestart()
{
DateTime now = DateTime.Now;
var dt = Properties.Settings.Default.RestartTime;
DateTime nextRestart = DateTime.Today.AddHours(dt.Hour).AddMinutes(dt.Minute).AddSeconds(dt.Second);
// If the restart time for today has already passed, set it for tomorrow
if (nextRestart <= now)
{
nextRestart = nextRestart.AddDays(1);
}
TimeSpan timeUntilRestart = nextRestart - now;
if (timer != null)
{
timer.Stop();
}
// Set up the timer to wait until the specified restart time
if (timer != null)
{
try
{
timer.Tick -= Timer_Tick;
timer.Stop();
}
catch (Exception ex)
{
}
}
timer = new DispatcherTimer
{
Interval = timeUntilRestart
};
timer.Tick += Timer_Tick;
timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
timer.Stop();
if (checkFlagTimer != null)
{
checkFlagTimer.Stop();
}
checkFlagTimer = new DispatcherTimer
{
Interval = TimeSpan.FromSeconds(30)
};
checkFlagTimer.Tick += CheckFlagTimer_Tick;
checkFlagTimer.Start();
}
private void CheckFlagTimer_Tick(object? sender, EventArgs e)
{
checkFlagTimer.IsEnabled = false;
if (AppData.GetTransactionCode() == "")
{
Log.Information("Restart app");
AppData.DeviceStatus.Description = "Restart App";
APIModels.SendEvent(AppData.DeviceStatus);
RestartApplication();
}
checkFlagTimer.IsEnabled = true;
}
private void RestartApplication()
{
string exePath = Process.GetCurrentProcess().MainModule.FileName;
Process.Start(exePath);
System.Windows.Application.Current.Shutdown();
} }
} }
} }
+8 -1
View File
@@ -58,7 +58,7 @@
Margin="10" Margin="10"
Click="SettingsButton_Click"/> Click="SettingsButton_Click"/>
<Button <Button
Content="Cấu hình" Content="Cấu hình CDM"
HorizontalAlignment="Stretch" HorizontalAlignment="Stretch"
Height="40" Height="40"
Margin="10" Margin="10"
@@ -71,6 +71,13 @@
Margin="10" Margin="10"
Padding="10" Padding="10"
Click="btnShutdownApp_Click"/> Click="btnShutdownApp_Click"/>
<Button
Content="Khởi động lại app"
HorizontalAlignment="Stretch"
Height="40"
Margin="10"
Padding="10"
Click="btnRestartApp_Click"/>
</StackPanel> </StackPanel>
<!-- Main Content Area --> <!-- Main Content Area -->
+27 -4
View File
@@ -1,6 +1,7 @@
using HandyControl.Tools.Extension; using HandyControl.Tools.Extension;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -23,12 +24,14 @@ namespace SafeBagDE70.Admin
LogViewerUC loguc; LogViewerUC loguc;
AdminConfigurationUC configuration; AdminConfigurationUC configuration;
UserManageUC userManage; UserManageUC userManage;
AdminSettingsUC settings;
public AdminWindow() public AdminWindow()
{ {
InitializeComponent(); InitializeComponent();
loguc= new LogViewerUC(); loguc= new LogViewerUC();
configuration = new AdminConfigurationUC(); configuration = new AdminConfigurationUC();
userManage=new UserManageUC(); userManage=new UserManageUC();
settings = new AdminSettingsUC();
this.MainContentControl.Content = loguc; this.MainContentControl.Content = loguc;
this.Loaded += AdminWindow_Loaded; this.Loaded += AdminWindow_Loaded;
} }
@@ -55,7 +58,7 @@ namespace SafeBagDE70.Admin
private void SettingsButton_Click(object sender, RoutedEventArgs e) private void SettingsButton_Click(object sender, RoutedEventArgs e)
{ {
this.MainContentControl.Content = settings;
} }
private void ReportsButton_Click(object sender, RoutedEventArgs e) private void ReportsButton_Click(object sender, RoutedEventArgs e)
@@ -70,10 +73,30 @@ namespace SafeBagDE70.Admin
private void btnShutdownApp_Click(object sender, RoutedEventArgs e) private void btnShutdownApp_Click(object sender, RoutedEventArgs e)
{ {
var bResult = MessageBox.Show("LƯU Ý, THAO TÁC NÀY SẼ LÀM MẤT TẤT CẢ DỮ LIỆU ĐANG THAO TÁC. " + if (AppData.GetTransactionCode() != "")
"CHỈ THỰC HIỆN KHI KHÔNG CÓ NGƯỜI DÙNG ĐANG THAO TÁC TRÊN MÁY","CẢNH BÁO",MessageBoxButton.OKCancel);
if (bResult == MessageBoxResult.OK)
{ {
MessageBox.Show("LƯU Ý, THAO TÁC NÀY SẼ LÀM MẤT TẤT CẢ DỮ LIỆU ĐANG THAO TÁC. " +
"HÃY HOÀN TẤT GIAO DỊCH ĐỂ TIẾP TỤC", "CẢNH BÁO", MessageBoxButton.OK);
}
else
{
System.Windows.Application.Current.Shutdown();
}
}
private void btnRestartApp_Click(object sender, RoutedEventArgs e)
{
if (AppData.GetTransactionCode() != "")
{
MessageBox.Show("LƯU Ý, THAO TÁC NÀY SẼ LÀM MẤT TẤT CẢ DỮ LIỆU ĐANG THAO TÁC. " +
"HÃY HOÀN TẤT GIAO DỊCH ĐỂ TIẾP TỤC", "CẢNH BÁO", MessageBoxButton.OK);
}
else
{
string exePath = Process.GetCurrentProcess().MainModule.FileName;
Process.Start(exePath);
System.Windows.Application.Current.Shutdown(); System.Windows.Application.Current.Shutdown();
} }
} }
+15
View File
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="SafeBagDE70.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<userSettings>
<SafeBagDE70.Properties.Settings>
<setting name="RestartTime" serializeAs="String">
<value />
</setting>
</SafeBagDE70.Properties.Settings>
</userSettings>
</configuration>
+6
View File
@@ -131,5 +131,11 @@ namespace SafeBagDE70
window.Width = screen.WorkingArea.Width; window.Width = screen.WorkingArea.Width;
window.Height = screen.WorkingArea.Height; window.Height = screen.WorkingArea.Height;
} }
protected override void OnExit(ExitEventArgs e)
{
// Release the mutex when the application is closed
mutex?.ReleaseMutex();
base.OnExit(e);
}
} }
} }
+37
View File
@@ -0,0 +1,37 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace SafeBagDE70.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.10.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public global::System.DateTime RestartTime {
get {
return ((global::System.DateTime)(this["RestartTime"]));
}
set {
this["RestartTime"] = value;
}
}
}
}
+9
View File
@@ -0,0 +1,9 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="SafeBagDE70.Properties" GeneratedClassName="Settings">
<Profiles />
<Settings>
<Setting Name="RestartTime" Type="System.DateTime" Scope="User">
<Value Profile="(Default)" />
</Setting>
</Settings>
</SettingsFile>
+12
View File
@@ -97,6 +97,11 @@
<Compile Update="EndSessionUC.xaml.cs"> <Compile Update="EndSessionUC.xaml.cs">
<SubType>Code</SubType> <SubType>Code</SubType>
</Compile> </Compile>
<Compile Update="Properties\Settings.Designer.cs">
<DesignTimeSharedInput>True</DesignTimeSharedInput>
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
</Compile>
<Compile Update="TimeoutUC.xaml.cs"> <Compile Update="TimeoutUC.xaml.cs">
<SubType>Code</SubType> <SubType>Code</SubType>
</Compile> </Compile>
@@ -114,4 +119,11 @@
</Compile> </Compile>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
</ItemGroup>
</Project> </Project>
+24 -16
View File
@@ -47,26 +47,34 @@ namespace VirtualKeyboard.Wpf
public static Task<string> OpenAsync(string initialValue = "") public static Task<string> OpenAsync(string initialValue = "")
{ {
if (_windowHost != null) throw new InvalidOperationException();
_tcs = new TaskCompletionSource<string>(); _tcs = new TaskCompletionSource<string>();
_windowHost = (Window)Activator.CreateInstance(_hostType); try
_windowHost.DataContext = new VirtualKeyboardViewModel(initialValue);
((ContentControl)_windowHost.FindName(_keyboardValueName)).Content = new KeyboardValueView();
((ContentControl)_windowHost.FindName(_keyboardName)).Content = new VirtualKeyboardView();
void handler(object s, CancelEventArgs a)
{ {
var result = GetResult(); if (_windowHost != null) throw new InvalidOperationException();
((Window)s).Closing -= handler;
_windowHost = null;
_tcs?.SetResult(result); _windowHost = (Window)Activator.CreateInstance(_hostType);
_tcs = null; _windowHost.DataContext = new VirtualKeyboardViewModel(initialValue);
((ContentControl)_windowHost.FindName(_keyboardValueName)).Content = new KeyboardValueView();
((ContentControl)_windowHost.FindName(_keyboardName)).Content = new VirtualKeyboardView();
void handler(object s, CancelEventArgs a)
{
var result = GetResult();
((Window)s).Closing -= handler;
_windowHost = null;
_tcs?.SetResult(result);
_tcs = null;
}
_windowHost.Closing += handler;
_windowHost.Owner = Application.Current.MainWindow;
_windowHost.Show();
} }
catch (Exception ex) {
_windowHost.Closing += handler; }
_windowHost.Owner = Application.Current.MainWindow;
_windowHost.Show();
return _tcs.Task; return _tcs.Task;
} }