Compare commits

..

2 Commits

Author SHA1 Message Date
6364f5f4d1 优化菜单样式和异步加载逻辑
在 `MaterialTrayMenuItem.xaml` 中添加命名空间,更新菜单项样式,增加悬停和点击动画效果,提升用户交互体验。新增上下文菜单样式,包含透明度和缩放动画。

在 `LoginWindow.xaml.cs` 中将 `Window_Loaded` 方法改为异步,增强窗口加载时的连接稳定性,并添加连接服务器的逻辑及错误处理。

在 `MainWindow.xaml` 中移除 `TextBox` 控件的 `Foreground` 属性设置,简化样式,保持界面整洁。
2025-06-08 09:12:24 +08:00
f4e2d0be38 添加账户管理和界面优化
在 `ChatDataModel.cs` 中添加 `Account` 类以存储临时账户信息。
修改 `TrayIconManager.cs` 的窗口关闭事件处理,移除通知显示并优化设置逻辑。
更新 `chatapi.cs` 中的服务器 URL 和 IP 地址。
调整 `LoginWindow.xaml` 的尺寸并添加 `Loaded` 事件处理,确保用户名和密码输入框正确绑定。
在 `LoginWindow.xaml.cs` 中实现读取和保存临时登录信息的功能。
修改 `MainWindow.xaml` 的选项卡定义,确保用户信息和设置选项卡正确显示。
更新 `MainWindow.xaml.cs` 中的登录和注册处理逻辑,确保正确处理服务器返回消息并清理资源。
2025-06-08 07:34:58 +08:00
8 changed files with 319 additions and 43 deletions

View File

@ -52,4 +52,12 @@ namespace chatclient.Data
File,//文件
System//系统信息
}
/// <summary>
/// 临时账户信息类,包含用户名和密码
/// </summary>
public class Account
{
public string? UserName { get; set; }
public string? UserPassword { get; set; }
}
}

View File

@ -1,7 +1,12 @@
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes">
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:local="clr-namespace:chatclient"
xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls">
<!-- 动画缓动函数 -->
<CubicEase x:Key="MenuEase" EasingMode="EaseOut"/>
<!-- Material Design 托盘菜单样式 -->
<Style x:Key="MaterialTrayMenuItem" TargetType="MenuItem" BasedOn="{StaticResource MaterialDesignMenuItem}">
<Setter Property="Background" Value="Transparent"/>
@ -13,27 +18,81 @@
<Setter.Value>
<ControlTemplate TargetType="MenuItem">
<Border x:Name="Border"
Background="Transparent"
CornerRadius="4"
SnapsToDevicePixels="True">
SnapsToDevicePixels="True"
Background="Transparent">
<Grid>
<materialDesign:Ripple Content="{TemplateBinding Header}" Background="Transparent" Foreground="{TemplateBinding Foreground}"
HorizontalContentAlignment="Stretch" VerticalContentAlignment="Center" Padding="{TemplateBinding Padding}"/>
<!-- 背景动画层 -->
<Rectangle x:Name="HoverRect"
Fill="#FF3D3D40"
Opacity="0"
RadiusX="4" RadiusY="4"/>
<!-- 涟漪效果层 -->
<materialDesign:Ripple
x:Name="Ripple"
Foreground="{TemplateBinding Foreground}"
Content="{TemplateBinding Header}"
VerticalContentAlignment="Center"
Padding="{TemplateBinding Padding}"
Background="Transparent"
HorizontalContentAlignment="Stretch"/>
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsHighlighted" Value="True">
<Setter TargetName="Border" Property="Background" Value="{DynamicResource MaterialDesignSelection}"/>
<!-- 悬停动画 -->
<Trigger Property="IsMouseOver" Value="True">
<Trigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetName="HoverRect"
Storyboard.TargetProperty="Opacity"
To="0.2"
Duration="0:0:0.2"
EasingFunction="{StaticResource MenuEase}"/>
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
<Trigger.ExitActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetName="HoverRect"
Storyboard.TargetProperty="Opacity"
To="0"
Duration="0:0:0.3"
EasingFunction="{StaticResource MenuEase}"/>
</Storyboard>
</BeginStoryboard>
</Trigger.ExitActions>
</Trigger>
<!-- 点击动画 -->
<EventTrigger RoutedEvent="PreviewMouseDown">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetName="Ripple"
Storyboard.TargetProperty="Opacity"
From="0.5" To="1"
Duration="0:0:0.15"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- 托盘菜单样式 -->
<Style x:Key="MaterialTrayMenu" TargetType="ContextMenu">
<!--<Setter Property="Background" Value="{DynamicResource MaterialDesignPaper}"/>-->
<Setter Property="Background" Value="{DynamicResource MaterialDesignPaper}"/>
<Setter Property="BorderBrush" Value="{DynamicResource MaterialDesignDivider}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="BorderBrush" Value="#A0252526"/>
<Setter Property="BorderThickness" Value="2"/>
<Setter Property="Padding" Value="8"/>
<Setter Property="SnapsToDevicePixels" Value="True"/>
<Setter Property="Effect">
@ -41,5 +100,57 @@
<DropShadowEffect BlurRadius="16" ShadowDepth="4" Color="#40000000"/>
</Setter.Value>
</Setter>
<Setter Property="RenderTransformOrigin" Value="0.5 0.5"/>
<Setter Property="RenderTransform">
<Setter.Value>
<ScaleTransform ScaleY="0.9"/>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ContextMenu">
<Border x:Name="MenuBorder"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="4"
Padding="{TemplateBinding Padding}">
<ItemsPresenter/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsOpen" Value="True">
<Trigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<!-- 透明度动画 -->
<DoubleAnimation
Storyboard.TargetProperty="Opacity"
From="0" To="1"
Duration="0:0:0.2"/>
<!-- 仅保留缩放动画(无位移) -->
<DoubleAnimation
Storyboard.TargetProperty="RenderTransform.ScaleY"
From="0.9" To="1"
Duration="0:0:0.3"
EasingFunction="{StaticResource MenuEase}"/>
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
<Trigger.ExitActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetProperty="Opacity"
To="0"
Duration="0:0:0.15"/>
</Storyboard>
</BeginStoryboard>
</Trigger.ExitActions>
</Trigger>
</Style.Triggers>
</Style>
</ResourceDictionary>

View File

@ -35,11 +35,6 @@ namespace chatclient.Data
// 取消关闭操作,改为最小化到托盘
e.Cancel = true;
_mainWindow.Hide();
// 显示通知
//_trayIcon.ShowBalloonTip("Application minimized",
// "The application is running in the system tray",
// BalloonIcon.Info);
}
private ContextMenu CreateContextMenu()
@ -70,7 +65,6 @@ namespace chatclient.Data
Style = (Style)Application.Current.Resources["MaterialTrayMenuItem"],
Icon = new PackIcon { Kind = iconKind, Width = 20, Height = 20 }
};
menuItem.Click += clickHandler;
return menuItem;
}
@ -94,7 +88,15 @@ namespace chatclient.Data
private void Settings_Click(object sender, RoutedEventArgs e)
{
// 实现设置逻辑
RestoreApplication();
Application.Current.Dispatcher.Invoke(() =>
{
var mainWindow = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();
if (mainWindow != null)
{
mainWindow.TabControl.SelectedItem = mainWindow.Settings;
}
});
}
private void Updates_Click(object sender, RoutedEventArgs e)

View File

@ -4,8 +4,8 @@ namespace chatclient.Data
{
internal class Server
{
public const string ServerUrl = "http://127.0.0.1:5001";
public const string ServerIP = "127.0.0.1";
public const string ServerUrl = "http://175.24.191.172:5001";
public const string ServerIP = "175.24.191.172";
public const int ServerPort = 8889;
}
internal class LoginData

View File

@ -7,8 +7,8 @@
xmlns:local="clr-namespace:chatclient"
xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls" x:Class="chatclient.LoginWindow"
mc:Ignorable="d"
Title="LoginWindow" Height="590" Width="330" MinHeight="590" MinWidth="330" MaxHeight="590" MaxWidth="330"
ResizeMode="NoResize" Closing="Window_Closing">
Title="LoginWindow" Height="540" Width="330" MinHeight="540" MinWidth="330" MaxHeight="540" MaxWidth="330"
ResizeMode="NoResize" Closing="Window_Closing" Loaded="Window_Loaded">
<TabControl>
<TabItem Header="登录账号" Cursor="Hand" Height="40">
@ -26,8 +26,8 @@
</Grid>
<Grid Width="280">
<StackPanel>
<TextBox VerticalAlignment="Top" materialDesign:HintAssist.Hint="用户名" Text="{Binding UserName}" Style="{StaticResource MaterialDesignOutlinedTextBox}" Margin="0,2,0,5"/>
<PasswordBox VerticalContentAlignment="Bottom" materialDesign:HintAssist.Hint="密码"
<TextBox x:Name="NameBox" VerticalAlignment="Top" materialDesign:HintAssist.Hint="用户名" Text="{Binding UserName}" Style="{StaticResource MaterialDesignOutlinedTextBox}" Margin="0,2,0,5"/>
<PasswordBox x:Name="PasswoedBox" VerticalContentAlignment="Bottom" materialDesign:HintAssist.Hint="密码"
materialDesign:TextFieldAssist.HasClearButton="False" Margin="0,10,0,5"
materialDesign:PasswordBoxAssist.Password="{Binding UserPassword}"
Style="{StaticResource MaterialDesignOutlinedRevealPasswordBox}"/>

View File

@ -11,6 +11,8 @@ using Microsoft.Win32;
using chatclient.Data;
using System.Net;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
using Microsoft.VisualBasic.ApplicationServices;
using MaterialDesignThemes.Wpf;
namespace chatclient
@ -101,21 +103,91 @@ namespace chatclient
}
else
{
log.Info($"向服务器发送注册HttpAPI请求(UserName:{SignName})");
SignRegistryUser(SignName, SignPassword1).ContinueWith(task =>
SignRegistryUser(SignName, SignPassword1).ContinueWith(Task =>
{
if (task.IsCompletedSuccessfully)
if (Task.IsCompletedSuccessfully)
{
log.Info("注册请求发送成功");
Application.Current.Dispatcher.Invoke(() =>
{
var loginWindow = Application.Current.Windows.OfType<LoginWindow>().FirstOrDefault();
if (loginWindow != null)
{
loginWindow.SignMsg = "注册请求已发送,请等待服务器响应";
}
});
}
else
{
log.Error("注册请求发送失败", task.Exception);
log.Error("注册请求发送失败", Task.Exception);
Application.Current.Dispatcher.Invoke(() =>
{
var loginWindow = Application.Current.Windows.OfType<LoginWindow>().FirstOrDefault();
if (loginWindow != null)
{
loginWindow.SignMsg = "注册请求发送失败,请检查网络连接";
}
});
}
});
//log.Info($"向服务器发送注册HttpAPI请求(UserName:{SignName})");
//SignRegistryUser(SignName, SignPassword1).ContinueWith(task =>
//{
// if (task.IsCompletedSuccessfully)
// {
// log.Info("注册请求发送成功");
// }
// else
// {
// log.Error("注册请求发送失败", task.Exception);
// }
//});
}
}
public static async Task SignRegistryUser(string Username, string Userpassword)
public static async Task SignRegistryUser(string Username, string Userpassword)
{
var SignData = new
{
type = "register",
username = Username,
password = Userpassword
};
string LoginJsonData = JsonSerializer.Serialize(SignData);
byte[] dataBytes = Encoding.UTF8.GetBytes(LoginJsonData);
log.Info($"向服务器发送注册请求(UserName:{Username})");
// 检查Socket是否可用
if (MainWindow.Client?.Connected == true)
{
MainWindow.Client.Send(dataBytes);
return;
}
log.Info("未连接服务器,尝试异步连接");
// 异步连接操作
await Task.Run(() =>
{
try
{
MainWindow.Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
MainWindow.Client?.Connect(IPAddress.Parse(Server.ServerIP), Server.ServerPort);
MainWindow.StartReceive();
MainWindow.Client?.Send(dataBytes);
}
catch (Exception ex)
{
log.Error($"连接失败: {ex.Message}");
MainWindow.Client?.Close();
Application.Current.Dispatcher.Invoke(() =>
{
var loginWindow = Application.Current.Windows.OfType<LoginWindow>().FirstOrDefault();
if (loginWindow != null)
{
loginWindow.SignMsg = "服务器连接失败";
}
});
}
});
}
public static async Task HttpSignRegistryUser(string Username, string Userpassword)
{
try
{
@ -205,17 +277,71 @@ namespace chatclient
}
});
}
public void Window_Loaded(object sender, RoutedEventArgs e)
public async void Window_Loaded(object sender, RoutedEventArgs e)
{
// 窗口加载时可以进行一些初始化操作
log.Info("登录窗口已加载");
// 如果需要从配置文件或其他地方加载保存的账号信息,可以在这里实现
// 例如UserName = LoadSavedUsername();
// Update("UserName");
if (MainWindow.Client?.Connected == false)
{
log.Info("未连接服务器,尝试连接");
// 异步连接操作
await Task.Run(() =>
{
try
{
MainWindow.Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
MainWindow.Client?.Connect(IPAddress.Parse(Server.ServerIP), Server.ServerPort);
MainWindow.StartReceive();
}
catch (Exception ex)
{
log.Error($"连接失败: {ex.Message}");
MainWindow.Client?.Close();
}
});
}
try
{
string tempPath = System.IO.Path.GetTempPath();
string filePath = System.IO.Path.Combine(tempPath, "chatclient_login.tmp");
if (System.IO.File.Exists(filePath))
{
string json = System.IO.File.ReadAllText(filePath, Encoding.UTF8);
var loginInfo = JsonSerializer.Deserialize <Account> (json);
if (loginInfo != null)
{
UserName = loginInfo.UserName!;
NameBox.Text = loginInfo.UserName;
UserPassword = loginInfo.UserPassword!;
PasswoedBox.Password = loginInfo.UserPassword;
SaveAccount = true;
}
}
}
catch (Exception ex)
{
log.Error("读取临时登录信息失败", ex);
}
}
public void Window_Closing(object sender, CancelEventArgs e)
{
if(MainWindow.token == null) Application.Current.Shutdown();
if (SaveAccount && !string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(UserPassword))
{
try
{
string tempPath = System.IO.Path.GetTempPath();
string filePath = System.IO.Path.Combine(tempPath, "chatclient_login.tmp");
var loginInfo = new { UserName, UserPassword };
string json = JsonSerializer.Serialize(loginInfo);
System.IO.File.WriteAllText(filePath, json, Encoding.UTF8);
}
catch (Exception ex)
{
log.Error("保存登录信息到临时文件失败", ex);
}
}
if (MainWindow.token == null) Application.Current.Shutdown();
}
}
}

View File

@ -11,7 +11,7 @@
Style="{StaticResource MaterialDesignWindow}" Closed="MainWindow_Closed" Loaded="MainWindow_Loaded">
<Grid>
<materialDesign:Card>
<TabControl VerticalContentAlignment="Bottom" materialDesign:ColorZoneAssist.Mode="PrimaryMid" Style="{StaticResource MaterialDesignNavigationRailTabControl}">
<TabControl x:Name="TabControl" VerticalContentAlignment="Bottom" materialDesign:ColorZoneAssist.Mode="PrimaryMid" Style="{StaticResource MaterialDesignNavigationRailTabControl}">
<materialDesign:NavigationRailAssist.FloatingContent>
<StackPanel>
<Button Style="{StaticResource MaterialDesignFloatingActionMiniLightButton}" Margin="12">
@ -20,7 +20,7 @@
<TextBlock Text="{Binding UserName}" TextAlignment="Center" MaxWidth="64" MaxHeight="64" TextWrapping="Wrap"/>
</StackPanel>
</materialDesign:NavigationRailAssist.FloatingContent>
<TabItem>
<TabItem x:Name="ChatMsg">
<TabItem.Header>
<StackPanel Width="auto" Height="auto">
<materialDesign:PackIcon Width="24" Height="24" HorizontalAlignment="Center" Kind="Message" />
@ -125,7 +125,7 @@
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBox x:Name="txtMessage" Grid.Row="0" materialDesign:HintAssist.Hint="输入消息..." AcceptsReturn="True" VerticalScrollBarVisibility="Auto"
TextWrapping="Wrap" MinHeight="50" MaxHeight="100" Margin="5" BorderBrush="#00000000" CaretBrush="#00673AB7" SelectionBrush="#00B39DDB"/>
TextWrapping="Wrap" MinHeight="50" MaxHeight="100" Margin="5" BorderBrush="#00000000"/>
<Button x:Name="btnSend" Grid.Row="1" Content="发送" MinWidth="80" Style="{StaticResource MaterialDesignRaisedButton}"
Click="SendMessage_Click" Width="20" HorizontalAlignment="Right" Margin="2,2,4,4"/>
</Grid>
@ -133,7 +133,7 @@
</Grid>
</Grid>
</TabItem>
<TabItem>
<TabItem x:Name="Settings">
<TabItem.Header>
<StackPanel Width="auto" Height="auto">
<materialDesign:PackIcon Width="24" Height="24" HorizontalAlignment="Center" Kind="Cog" />

View File

@ -21,6 +21,7 @@ using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Windows.Threading;
using System.Collections.Specialized;
using Hardcodet.Wpf.TaskbarNotification;
[assembly: XmlConfigurator(ConfigFile = "config/log4net.config", Watch = true)]
namespace chatclient
@ -132,9 +133,9 @@ namespace chatclient
var Type = JsonSerializer.Deserialize<RegisterData>(msg);
if (Type != null)
{
var LoginResponse = JsonSerializer.Deserialize<LoginResultData>(msg);
if (Type.type == "login_1")
{
var LoginResponse = JsonSerializer.Deserialize<LoginResultData>(msg);
if (LoginResponse!.status == "success" && LoginResponse != null)
{
token = LoginResponse.token;
@ -176,9 +177,10 @@ namespace chatclient
});
}
}
else if (Type.type == "login_0" && LoginResponse != null)
else if (Type.type == "login_0")
{
log.Warn($"登录失败: {LoginResponse.message}\nMsg:{msg}");
var LoginResponse = JsonSerializer.Deserialize<LoginResultData>(msg);
log.Warn($"登录失败: {LoginResponse!.message}\nMsg:{msg}");
Application.Current.Dispatcher.Invoke(() =>
{
var loginWindow = Application.Current.Windows.OfType<LoginWindow>().FirstOrDefault();
@ -188,6 +190,29 @@ namespace chatclient
}
});
}
else if (Type.type == "register_1")
{
var SignResponse = JsonSerializer.Deserialize<SignResultData>(msg);
log.Warn($"注册成功\nMsg:{msg}");
Application.Current.Dispatcher.Invoke(async () =>
{
//var loginWindow = Application.Current.Windows.OfType<LoginWindow>().FirstOrDefault();
await LoginWindow.Login(true,LoginWindow.SignName, LoginWindow.SignPassword1);
});
}
else if (Type.type == "register_0")
{
var SignResponse = JsonSerializer.Deserialize<SignResultData>(msg);
log.Warn($"注册失败: {SignResponse!.message}\nMsg:{msg}");
Application.Current.Dispatcher.Invoke(() =>
{
var loginWindow = Application.Current.Windows.OfType<LoginWindow>().FirstOrDefault();
if (loginWindow != null)
{
loginWindow.SignMsg = "用户名已存在";
}
});
}
else if (Type.type == "chat")
{
var chat = JsonSerializer.Deserialize<ChatRegisterData>(msg);
@ -345,12 +370,16 @@ namespace chatclient
}
private void MainWindow_Closed(object sender, System.EventArgs e)
{
log.Info("MainWindow 关闭事件触发,清理资源");
// 清理资源
Client?.Shutdown(SocketShutdown.Both);
Client?.Close();
log.Info("关闭Socket连接");
Client?.Dispose();
token = null;
_trayManager?.Dispose();
log.Info("托盘图标管理器已释放资源");
log.Info("Bye!");
}
}
}