WPF实例系列一:登录、注册界面设计
文章目录
- WPF实例系列一:登录、注册界面设计
- 前言
- 一、实例演示
- 1. 登录界面展示
- 2. 注册界面展示
- 3. 数据存储
- 4. 效果演示
- 二、结构及源码
- 1.主界面跳转登录界面设计
- 2.登录界面设计
- 3.注册界面设计
- 4.Excel保存数据类设计
- 5.源码
- 三、补充
- 1.增加Mysql数据库存储账户数据
前言
本实例将展示利用WPF设计登录界面、注册界面,并实现相应的功能,其中账户数据将存储在excel表中(补充:增加Mysql数据库存储账户数据)。
一、实例演示
1. 登录界面展示
2. 注册界面展示
3. 数据存储
4. 效果演示
二、结构及源码
1.主界面跳转登录界面设计
MainWindow.xaml.cs跳转登录界面代码如下:
using System;
using System.Windows;
using System.Windows.Threading;namespace sample5
{/// <summary>/// MainWindow.xaml 的交互逻辑/// </summary>public partial class MainWindow : Window{//public int play_state = 1; public MainWindow(){InitializeComponent();#region 登录界面加载及验证//显示登陆界面,验证后返回。LoginWindow loginWindow = new LoginWindow();loginWindow.ShowDialog();if (loginWindow.DialogResult != Convert.ToBoolean(1)){this.Close();}//显示登陆界面 结束#endregion }}}
2.登录界面设计
Xaml代码如下(添加1个Nuget库:MaterialDesignThemes.3.1.0-ci981 ;可参考):
<Window x:Class="sample5.LoginWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"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:local="clr-namespace:sample5"mc:Ignorable="d"Title="用户登录" Height="500" Width="350" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" WindowStyle="None" MouseLeftButtonDown="MoveWindow_MouseLeftButtonDown"FontFamily="Segoe UI Emoji"><Grid><Rectangle Height="280" VerticalAlignment="Top"><Rectangle.Fill><LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"><GradientStop Color="#FF2281D1"/><GradientStop Color="#FF34268A" Offset="1"/><GradientStop Color="#FF33288B" Offset="0.546"/></LinearGradientBrush></Rectangle.Fill></Rectangle><Rectangle Height=" 220" VerticalAlignment="Bottom" ><Rectangle.Fill><SolidColorBrush Color="Snow" /></Rectangle.Fill></Rectangle><Rectangle Width="280" Height="240" VerticalAlignment="Bottom" Margin="0,80" RadiusY="10" RadiusX="10" Fill="White"><Rectangle.Effect><DropShadowEffect BlurRadius="15" Direction="0" RenderingBias="Quality" ShadowDepth="1" Color="#FFBBBBBB"/></Rectangle.Effect></Rectangle><Grid VerticalAlignment="Bottom" Margin="35,80" Height="240"><Label Content="登录" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="5" Foreground="Gray" FontSize="18"/><StackPanel VerticalAlignment="Center" Margin="15"><TextBox x:Name="Account" Margin="0,5" materialDesign:HintAssist.Hint="账号" Style="{StaticResource MaterialDesignFloatingHintTextBox}" FontFamily="Champagne & Limousines" FontSize="16"/><PasswordBox x:Name="Password" Margin="0,5" materialDesign:HintAssist.Hint="密码" Style="{StaticResource MaterialDesignFloatingHintPasswordBox}" FontFamily="Champagne & Limousines" FontSize="16"/></StackPanel></Grid><Button Width="150" HorizontalAlignment="Center" VerticalAlignment="Bottom" Margin="0,65" Content="LOGIN" Click="Login_Button"/><TextBlock Text="注册账户" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="60 40" FontSize="13" Foreground="Gray" Cursor="Hand" MouseLeftButtonDown="TextBlock_MouseLeftButtonDown"/><TextBlock Text="忘记密码?" HorizontalAlignment="Right " VerticalAlignment="Bottom" Margin="60 40" FontSize="13" Foreground="Gray" Cursor="Hand"/><Button HorizontalAlignment="Right" VerticalAlignment="Top" Background="{x:Null}" BorderBrush="{x:Null}" Click="Close_Click" ><materialDesign:PackIcon Kind="Close"/></Button><Border CornerRadius="30" BorderBrush="#FF2281D1" BorderThickness="2" Width="100" Height="100" VerticalAlignment="Top" Margin="30"><Border.Background><ImageBrush ImageSource="./picture/Loginbackground.jpg"/></Border.Background></Border></Grid>
</Window>
后台代码如下(LoginWindow.xaml.cs):
using System;
using System.Collections;
using System.Windows;
using System.Windows.Input;
using Window = System.Windows.Window;namespace sample5
{/// <summary>/// LoginWindow.xaml 的交互逻辑/// </summary>public partial class LoginWindow : Window{public string UserName;public string UserPassword;public int border = 1;public static Hashtable userall_harsh;public LoginWindow(){InitializeComponent();}private void MoveWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e){DragMove();}private void Close_Click(object sender, RoutedEventArgs e){this.Close();}private void Login_Button(object sender, RoutedEventArgs e){ExcelSave excel1 = new ExcelSave();userall_harsh = excel1.readExcel();if (userall_harsh == null){MessageBox.Show("无此账户,请先注册!");return;}else{ IDictionaryEnumerator myEnumerator = userall_harsh.GetEnumerator(); //读取harshtable中的key和value值while (myEnumerator.MoveNext()) //将枚举数推到集合的下一元素,若为空,则退出循环{UserName = myEnumerator.Key.ToString(); //key值赋给UserNameUserPassword = myEnumerator.Value.ToString(); //value值赋给UserPasswordif (Account.Text.ToString() == UserName && Password.Password.ToString() == UserPassword){this.DialogResult = Convert.ToBoolean(1);this.Close();break;}else if (border<=userall_harsh .Count-1) //给循环一边界,若循环到所存数据最后一个数仍然不正确,则执行else语句{border++;} elseMessageBox.Show("账号或密码错误,请重试!");}}}//“注册账户”TextBlock触发事件private void TextBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e){RegisterWindow register1 = new RegisterWindow(); //Login为窗口名,把要跳转的新窗口实例化this.Close(); //关闭当前窗口register1.ShowDialog(); //打开新窗口 }}
}
3.注册界面设计
Xaml代码如下:
<Window x:Class="sample5.RegisterWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"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:local="clr-namespace:sample5"mc:Ignorable="d"Title="用户登录" Height="500" Width="350" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" WindowStyle="None" MouseLeftButtonDown="MoveWindow_MouseLeftButtonDown"FontFamily="Segoe UI Emoji"><Grid><Rectangle Height="280" VerticalAlignment="Top"><Rectangle.Fill><LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"><GradientStop Color="#FF2281D1"/><GradientStop Color="#FF34268A" Offset="1"/><GradientStop Color="#FF33288B" Offset="0.546"/></LinearGradientBrush></Rectangle.Fill></Rectangle><Rectangle Height=" 220" VerticalAlignment="Bottom" ><Rectangle.Fill><SolidColorBrush Color="Snow" /></Rectangle.Fill></Rectangle><Rectangle Width="280" Height="240" VerticalAlignment="Bottom" Margin="0,80" RadiusY="10" RadiusX="10" Fill="White" ><Rectangle.Effect><DropShadowEffect BlurRadius="15" Direction="0" RenderingBias="Quality" ShadowDepth="1" Color="#FFBBBBBB"/></Rectangle.Effect></Rectangle><Grid VerticalAlignment="Bottom" Margin="35,80" Height="240"><Label Content="用户注册" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="5" Foreground="Black" FontSize="18"/><StackPanel VerticalAlignment="Center" Margin="20"><TextBox x:Name="Re_Account" Margin="0,5" materialDesign:HintAssist.Hint="请输入账号" Style="{StaticResource MaterialDesignFloatingHintTextBox}" FontFamily="Champagne & Limousines" FontSize="16"/><PasswordBox x:Name="Re_Password" Margin="0,5" materialDesign:HintAssist.Hint="请输入密码" Style="{StaticResource MaterialDesignFloatingHintPasswordBox}" FontFamily="Champagne & Limousines" FontSize="16"/><PasswordBox x:Name="Re_PasswordAgain" Margin="0,5" materialDesign:HintAssist.Hint="请确认密码" Style="{StaticResource MaterialDesignFloatingHintPasswordBox}" FontFamily="Champagne & Limousines" FontSize="16"/></StackPanel></Grid><Button Width="150" HorizontalAlignment="Center" VerticalAlignment="Bottom" Margin="0,65" Content="Register" Click="Register_Button"/><Border CornerRadius="30" BorderBrush="#FF2281D1" BorderThickness="2" Width="100" Height="100" VerticalAlignment="Top" Margin="30"><Border.Background><ImageBrush ImageSource="./picture/Registerbackground.jpg"/></Border.Background></Border><Button HorizontalAlignment="Right" VerticalAlignment="Top" Background="{x:Null}" BorderBrush="{x:Null}" Click="ReClose_Click" ><materialDesign:PackIcon Kind="Close"/></Button></Grid>
</Window>
后台代码如下:
using System;
using System.Collections;
using System.Windows;
using System.Windows.Input;
using Window = System.Windows.Window;namespace sample5
{/// <summary>/// RegisterWindow.xaml 的交互逻辑/// </summary>public partial class RegisterWindow : Window{public static Hashtable userall;public RegisterWindow(){InitializeComponent();}private void MoveWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e){DragMove();}private void ReClose_Click(object sender, RoutedEventArgs e){this.Close();}private void Register_Button(object sender, RoutedEventArgs e){string u = Re_Account.Text.ToString();string p = Re_Password.Password.ToString();string rp = Re_PasswordAgain.Password.ToString();ExcelSave excel = new ExcelSave();if (String.IsNullOrEmpty(u)){MessageBox.Show("user is not null");return;}if (String.IsNullOrEmpty(p)){MessageBox.Show("password is not null");return;}if (String.IsNullOrEmpty(rp)){MessageBox.Show("Repassword is not null");return;}if (!p.Equals(rp)){MessageBox.Show("password is not equals repassword");return;}userall = excel.readExcel(); //读取excel数据if (userall == null){userall = new Hashtable();userall.Add(u, p);}else{bool isexist = userall.ContainsKey(u); //判断用户是否存在if (isexist){MessageBox.Show("user is exist!");return;}else{userall.Add(u, p);Console.WriteLine(userall.Count);}}System.Windows.Application.Current.Properties["users"] = userall; //类似于Session的功能,用户登录后,可以将用户的信息保存在Properties中。excel.InsertExcel(u, p);MessageBox.Show("regist success!");MainWindow main = new MainWindow();main.WindowStartupLocation = WindowStartupLocation.Manual; //使新窗口位置在原来的位置上main.Left = this.Left; //使新窗口位置在原来的位置上main.Top = this.Top; //使新窗口位置在原来的位置上this.Close();main.ShowDialog(); //打开新窗口 }}
}
4.Excel保存数据类设计
学习使用Csharp处理excel表,创建ExcelSave.cs:
using System;
using Excel = Microsoft.Office.Interop.Excel;
using System.Collections;
using System.Windows;namespace sample5
{public class ExcelSave{Excel.Application ExcelApp = new Excel.Application();#region 创建excel工作簿public void InsertExcel(string u, string p){//1.创建Exceltry{//2.打开已经存在的工作簿string path = "C:\\Users\\非黑不即白\\Desktop\\code.xlsx";ExcelApp.Workbooks.Open(path, ReadOnly: false);//3.ExcelApp.Cells[1, 1].Value = "username";ExcelApp.Cells[1, 2].Value = "password";int RowCount = ExcelApp.ActiveSheet.UsedRange.Rows.Count + 1;//ExcelApp.ActiveSheet.Rows[RowCount].Insert(u, p);ExcelApp.Cells[RowCount, 1].Value = u;ExcelApp.Cells[RowCount, 2].Value = p;ExcelApp.DisplayAlerts = false; //保存Excel的时候,不弹出是否保存的窗口直接进行保存 //4.保存工作表ExcelApp.ActiveWorkbook.Save();}catch{MessageBox.Show("导出文件保存失败,可能原因该文件已打开!", "警告!");}finally{//5.关闭工作簿ExcelApp.ActiveWorkbook.Close();//6.退出excelExcelApp.Quit();// PublicMethod.Kill(ExcelApp);}}#endregion#region 读取excel工作簿数据public Hashtable readExcel(){try{//2.打开已经存在的工作簿string path = "C:\\Users\\非黑不即白\\Desktop\\code.xlsx";//ExcelApp.Workbooks.Open(path, ReadOnly: true);Hashtable h = new Hashtable();Excel.Workbook wb = ExcelApp.Application.Workbooks.Open(path, ReadOnly: true); //取得工作簿Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets.get_Item(1);int rowsint = ws.UsedRange.Cells.Rows.Count; //得到行数Excel.Range rng1 = ws.Cells.get_Range("A2", "A" + rowsint); // 取得数据范围区域(不包括标题列)Excel.Range rng2 = ws.Cells.get_Range("B2", "B" + rowsint);string[,] arry = new string[rowsint - 1, 2]; //将新值赋给一个数组if (rowsint <= 1){//MessageBox.Show("无账户信息,请先注册!"); LoginWindow已做判断,无需重复return null;}else{if (rowsint == 2) //解决表格有一个数据用户,再添加时报错的问题{arry[0, 0] = rng1.Value2.ToString(); //rng.value2获取单元格数据arry[0, 1] = rng2.Value2.ToString();h.Add(rng1.Value2.ToString(), rng2.Value2.ToString());Console.WriteLine(rng1.Value2.ToString() + " :" + rng2.Value2.ToString());return h;}else{for (int i = 1; i <= rowsint - 1; i++){arry[i - 1, 0] = rng1.Value2[i, 1].ToString(); //rng.value2获取单元格数据arry[i - 1, 1] = rng2.Value2[i, 1].ToString();h.Add(rng1.Value2[i, 1].ToString(), rng2.Value2[i, 1].ToString());Console.WriteLine(rng1.Value2[i, 1].ToString() + " :" + rng2.Value2[i, 1].ToString());}return h;}}}catch{MessageBox.Show("read excel error");return null;}finally{//5.关闭工作簿ExcelApp.ActiveWorkbook.Close();//6.退出excelExcelApp.Quit();//PublicMethod.Kill(ExcelApp); //关闭excel后台进程,此处无需添加}}#endregion}/* 关闭excel后台进程public class PublicMethod{[DllImport("User32.dll", CharSet = CharSet.Auto)]public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);public static void Kill(Excel.Application excel){IntPtr t = new IntPtr(excel.Hwnd);//得到这个句柄,具体作用是得到这块内存入口 int k = 0;GetWindowThreadProcessId(t, out k); //得到本进程唯一标志kSystem.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k); //得到对进程k的引用p.Kill(); //关闭进程k}}*/
}
5.源码
结构总览:
源码:点击跳转地址
三、补充
1.增加Mysql数据库存储账户数据
using System;
using System.Collections;
using System.Windows;
//引入MySQL
using MySql.Data.MySqlClient;namespace SheepMusic
{public class Mysql_Code{static string constring = "server = localhost ;port=3306; uid = root; pwd = djz19960824; database = test; charset=utf8;"; //定义连接mysql字符串MySqlConnection sqlCnn = new MySqlConnection(constring); //连接mysql#region 读取Mysql数据库信息public Hashtable Mysql_read(){string username;string password;string cmdstring = "select * from code"; //写入sqlMySqlCommand sqlCmd = new MySqlCommand(cmdstring, sqlCnn); //创建命令对象 Hashtable h = new Hashtable();try{sqlCnn.Open(); //打开数据库MySqlDataReader rec = sqlCmd.ExecuteReader();while (rec.Read()){username = rec.GetString(0);password = rec.GetString(1);h.Add(username, password);}return h;}catch (Exception ex){MessageBox.Show(ex.Message, "error");return null;}finally{sqlCnn.Close();}}#endregion#region 外部写入Mysql数据库信息public void Mysql_insert(string u, string p){try{sqlCnn.Close();sqlCnn.Dispose();string insertstring = "insert into code values('" + u + "','" + p + "')";MySqlCommand sqlInsert = new MySqlCommand(insertstring, sqlCnn);sqlCnn.Open();sqlInsert.ExecuteNonQuery(); //插入数据}catch (Exception ex){MessageBox.Show(ex.Message, "error");}finally{sqlCnn.Close();}}#endregion#region 修改Mysql数据库数据信息public void Mysql_reset(string u, string p){try{sqlCnn.Close();sqlCnn.Dispose();string resetstring = "update code set password ='" + p + "' where user = '" + u + "'";MySqlCommand sqlReset = new MySqlCommand(resetstring, sqlCnn);sqlCnn.Open();sqlReset.ExecuteNonQuery(); //插入数据}catch (Exception ex){MessageBox.Show(ex.Message, "error");}finally{sqlCnn.Close();}}#endregion}
}
参考文献
1. 少量代码设计一个登录界面 - .NET CORE(C#) WPF开发
2.页面跳转
3.WPF注册登录页面,同时将注册信息保存到一个excel中
4.C#导出数据到Excel的几种方法
补充学习