目錄
功能概述
實現思路
一、程序入口(Program.cs)
二、登錄用戶控件(Login.cs)
2.1 控件初始化與密碼顯示邏輯
2.2 登錄控件設計器(Login.Designer.cs)
三、主窗體(Form1.cs)
3.1 初始化與數據加載
3.2 登錄功能實現
3.3 數據持久化(文件操作)
3.4 記錄管理(刪除功能+鼠標右擊選中)
3.5 主窗體設計器(Form1.Designer.cs)
四、模塊間關系說明
設計器代碼說明
功能亮點
在日常開發中,我們經常需要記錄用戶的登錄信息以便后續查看和管理。今天我將分享一個基于 WinForm 的簡單用戶登錄記錄器實現,該程序能夠記錄用戶登錄時間和賬號信息,并支持對記錄進行管理。
功能概述
這個登錄記錄器主要包含以下功能:
- 用戶登錄界面(賬號、密碼輸入)
- 登錄記錄顯示(右側列表)
- 登錄記錄持久化存儲(保存到本地文件)
- 記錄管理(右鍵菜單刪除功能)
- 鼠標右鍵選中功能(鼠標右鍵Mouse UP事件)
- 登錄時間記錄(DateTime)
- 復合控件的使用
實現思路
- 使用 WinForm 構建主界面和登錄控件
- 通過 JSON 格式將登錄記錄保存到本地文件
- 實現登錄記錄的增刪查功能
- 提供右鍵菜單用于刪除記錄
一、程序入口(Program.cs)
這是應用程序的啟動點,負責初始化和啟動主窗體:
using System;
using System.Windows.Forms;namespace UMP
{internal static class Program{/// <summary>/// 應用程序的主入口點/// </summary>[STAThread] // 標記為單線程單元,WinForm 必須使用此特性static void Main(){// 啟用視覺樣式,使界面更美觀Application.EnableVisualStyles();// 設置文本渲染方式為默認Application.SetCompatibleTextRenderingDefault(false);// 啟動主窗體Application.Run(new Form1());}}
}
核心作用:作為程序的啟動器,初始化應用程序并加載主窗體。
二、登錄用戶控件(Login.cs)
這是一個自定義用戶控件,封裝了登錄相關的界面元素和功能:
2.1 控件初始化與密碼顯示邏輯
using System.Windows.Forms;namespace UMP
{public partial class Login : UserControl{// 定義委托用于跨控件通信public delegate void AddAccountToForm(string accountInfo);public event AddAccountToForm OnAccountAdded;public Login(){InitializeComponent();// 初始化密碼框,用*隱藏密碼textBox2.PasswordChar = '*';}// 密碼顯示/隱藏切換private void checkBox1_CheckedChanged(object sender, EventArgs e){// 復選框選中時顯示明文,否則顯示*textBox2.PasswordChar = checkBox1.Checked ? '\0' : '*';}}
}
核心作用:
- 提供賬號密碼輸入界面
- 實現密碼顯示 / 隱藏功能
- 定義事件委托用于與主窗體通信
2.2 登錄控件設計器(Login.Designer.cs)
設計器代碼定義了登錄控件的界面元素:
namespace UMP
{partial class Login{private System.ComponentModel.IContainer components = null;protected override void Dispose(bool disposing){if (disposing && (components != null)){components.Dispose();}base.Dispose(disposing);}private void InitializeComponent(){// 初始化各種控件this.label1 = new System.Windows.Forms.Label();this.textBox1 = new System.Windows.Forms.TextBox(); // 賬號輸入框this.textBox2 = new System.Windows.Forms.TextBox(); // 密碼輸入框this.label2 = new System.Windows.Forms.Label();this.label3 = new System.Windows.Forms.Label(); // "用戶登錄"標題this.checkBox1 = new System.Windows.Forms.CheckBox(); // 顯示密碼復選框this.button1 = new System.Windows.Forms.Button(); // 登錄按鈕// 省略控件屬性設置代碼...// 綁定事件this.checkBox1.CheckedChanged += new System.EventHandler(this.checkBox1_CheckedChanged);}// 定義控件變量,供外部訪問public System.Windows.Forms.TextBox textBox1;public System.Windows.Forms.TextBox textBox2;public System.Windows.Forms.Button button1;}
}
核心作用:通過代碼定義了登錄界面的所有控件及其布局、樣式和事件綁定。
三、主窗體(Form1.cs)
主窗體是程序的主界面,負責協調各部分功能:
3.1 初始化與數據加載
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Windows.Forms;namespace UMP
{public partial class Form1 : Form{// 定義數據存儲路徑(當前目錄下的"賬號.txt")private string FilePath => Path.Combine(Directory.GetCurrentDirectory(), "賬號.txt");public Form1(){InitializeComponent();// 綁定登錄按鈕的點擊事件login1.button1.Click += Button1_Click;// 加載已保存的登錄記錄try{using (StreamReader sr = new StreamReader(FilePath)){string data = sr.ReadToEnd();// 解析JSON數據JArray jsondata = JsonConvert.DeserializeObject<JArray>(data);if (jsondata != null){// 將記錄添加到列表框foreach (string jobj in jsondata){listBox1.Items.Add(jobj);} }}}catch (FileNotFoundException){// 文件不存在時不做處理(首次運行時正常)}catch (Exception ex){MessageBox.Show($"加載數據出錯: {ex.Message}");}}}
}
核心作用:
- 定義數據存儲路徑
- 初始化界面并綁定事件
- 程序啟動時加載歷史登錄記錄
3.2 登錄功能實現
// 登錄按鈕點擊事件處理
private void Button1_Click(object sender, EventArgs e)
{// 驗證賬號密碼不為空if (login1.textBox1.Text != "" && login1.textBox2.Text != ""){// 獲取當前時間DateTime time = DateTime.Now;// 添加登錄記錄到列表listBox1.Items.Add($"登錄時間:{time} 登錄賬號:{login1.textBox1.Text}");// 保存記錄到文件Writedata();}else{// 提示用戶輸入賬號密碼MessageBox.Show("請輸入賬號和密碼!");}
}
核心作用:
- 驗證用戶輸入
- 記錄登錄信息(時間 + 賬號)
- 觸發數據保存操作
3.3 數據持久化(文件操作)
// 將登錄記錄保存到文件
public void Writedata()
{try{// 將列表框中的數據序列化為JSON格式string Jsondata = JsonConvert.SerializeObject(listBox1.Items, Formatting.Indented);// 寫入文件using (StreamWriter sw = new StreamWriter(FilePath, false, Encoding.UTF8)){sw.WriteLine(Jsondata);}}catch (Exception ex){MessageBox.Show($"保存數據出錯: {ex.Message}");}
}
核心作用:使用 JSON 格式將登錄記錄持久化到本地文件,保證程序重啟后數據不丟失。
3.4 記錄管理(刪除功能+鼠標右擊選中)
#region 刪除int index;private void 刪除賬號ToolStripMenuItem_Click(object sender, EventArgs e){listBox1.Items.RemoveAt(index); // 從列表移除Writedata();}//鼠標右鍵選擇private void listBox1_MouseUp(object sender, MouseEventArgs e){if (e.Button == MouseButtons.Right){//選中當前點擊位置的數據 的索引index = listBox1.IndexFromPoint(e.Location);//將當前點擊位置的數據 選中listBox1.SelectedIndex = index;//判斷但當前是否選中數據if (index >= 0){//選中點擊的項listBox1.SetSelected(index, true);刪除賬號ToolStripMenuItem.Enabled = true;}else{//listBox1.SelectedIndex = -1;listBox1.ClearSelected();刪除賬號ToolStripMenuItem.Enabled = false;}}}#endregion
核心作用:實現登錄記錄的刪除功能,包括右鍵菜單交互和文件數據更新。
3.5 主窗體設計器(Form1.Designer.cs)
定義主窗體的布局和控件:
namespace UMP
{partial class Form1{private System.ComponentModel.IContainer components = null;protected override void Dispose(bool disposing){if (disposing && (components != null)){components.Dispose();}base.Dispose(disposing);}private void InitializeComponent(){this.components = new System.ComponentModel.Container();this.listBox1 = new System.Windows.Forms.ListBox(); // 顯示登錄記錄的列表this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);this.刪除賬號ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); // 刪除菜單this.login1 = new UMP.Login(); // 登錄控件// 省略控件屬性設置...// 綁定事件this.listBox1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.listBox1_MouseUp);this.刪除賬號ToolStripMenuItem.Click += new System.EventHandler(this.刪除賬號ToolStripMenuItem_Click);}// 定義控件變量private System.Windows.Forms.ListBox listBox1;private Login login1;private System.Windows.Forms.ContextMenuStrip contextMenuStrip1;private System.Windows.Forms.ToolStripMenuItem 刪除賬號ToolStripMenuItem;}
}
核心作用:定義主窗體的布局,包含左側的登錄控件和右側的記錄列表。
四、模塊間關系說明
- 調用關系:Program → Form1 → Login(主窗體包含登錄控件)
- 數據流向:
- 用戶輸入 → Login 控件 → Form1 處理 → 保存到文件
- 文件 → Form1 加載 → 顯示到 listBox1
- 事件傳遞:Login 控件的按鈕事件在 Form1 中處理,實現了控件間的解耦
通過這樣的模塊化設計,代碼結構清晰,各部分職責明確,便于維護和擴展。
設計器代碼說明
除了上述核心代碼外,我們還需要設計器代碼來定義界面布局。設計器代碼主要包含:
- Form1.Designer.cs:定義主窗體布局,包含一個列表框(用于顯示記錄)和一個登錄用戶控件
- Login.Designer.cs:定義登錄控件的布局,包含賬號輸入框、密碼輸入框、顯示密碼復選框和登錄按鈕
設計器代碼由 Visual Studio 自動生成,主要定義了控件的位置、大小、字體等屬性以及控件間的層次關系。
功能亮點
- 數據持久化:使用 JSON 格式將登錄記錄保存到本地文件,下次啟動程序時自動加載
- 用戶體驗:密碼框支持顯示 / 隱藏切換,操作更友好
- 記錄管理:通過右鍵菜單可以方便地刪除不需要的記錄
- 代碼結構:使用用戶控件分離登錄功能,使代碼結構更清晰