實作C# Form的登出再重新登入功能

一般在開發應用程式時都會在執行程式時先顯示一個對話視窗要求使用者輸入登入資訊。正確後再登入到主畫面中。

在主畫面中也會登供一個登出的功能,以便讓使用者重新登入。看是用其它的使用者帳號登入或是登入到不同的環境中。

不過在C#中好像沒有辦法直接支援這種登出登入模式。所以必須自行實作。目前我實作的方式就是在主視窗中宣告一個公用變數來記錄是否要進行重新登入,並接收FormClosiing事件詢問使用者是否要重新登入。

程式碼如下:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace TestFormLogout
{
    public partial class Form1 : Form
    {
        /// <summary>
        /// 記錄是否要進行重新登入
        /// </summary>
        public bool isReLogin = false;

        public Form1()
        {
            InitializeComponent();
        }

        private void btnLogout_Click(object sender, EventArgs e)
        {
            this.Close(); 
        }

        private void OnClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("是否重新登入?", "重新登入", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                // 設定進行重新登入
                isReLogin = true;
            }
        }
    }
}


在程式的進入點mail()中,也要配合做一些修改。它必須接收FormClosed()事件,並在這個載易件處理函式中取得目前主視窗關閉後是否要重新登入的設定值。以便處理重新登入。重新登入則是簡單地用do-while方式來實作。程式碼如下:


using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace TestFormLogout
{
    static class Program
    {
        /// <summary>
        /// 應用程式的主要進入點。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            do
            {
                // 自己建構一個新的Form1物件,並掛載FormClosed函式
                Form1 f1 = new Form1();
                f1.FormClosed += new FormClosedEventHandler(f1_FormClosed);
                Application.Run(f1);
            } while (isReLogin); // 利用do-while()方式來實作重新登入
        }

        static bool isReLogin = false;
        static void f1_FormClosed(object sender, FormClosedEventArgs e)
        {
            // 在FormClosed事件中,確認是否為Form1型別。是的話就取得它所設定的是否重新登入變數。
            if (sender is Form1)
            {
                Form1 f1 = sender as Form1;
                isReLogin = f1.isReLogin;
            }
        }
    }
}

留言

這個網誌中的熱門文章

DOS Batch指令檔中如何記錄log資訊

用捷徑方式執行需帶入命令列參數的Windows Form程式

使用regular expression來match中括號(square bracket)