最近有個需求,要在Windows Form中做出如下的軟體授權同意畫面,使用者必須閱讀完授權書晝面,按下"接受"才可以繼續使用。(會仔細讀軟體授權書的人請舉手! 那個戴眼鏡的胖子,你確定你有? 要誠實哦... 很好,跟我想的一樣,Nobody!)

以下是我這次想出來的寫法,有幾項特色,介紹給還不熟Windows Form的朋友參考:

第一,由於授權書圖文並茂、還有一堆排版設定,我決定用Word將它存成rtf後,再直接用RichTextBox載入,超級省事!!

第二,不想跟著一個rtf檔拖油瓶,我希望能效法綠色軟體一個EXE檔打死。所以將rtf檔拖入專案內設為Embedded Resource, 如此檔案內容會被包進EXE中。要取用時,只需呼叫Assembly.GetManifestResourceStream(),挺簡便的。缺點是更新rtf內容時必須Rebuild。

第三,利用ShowDialog()要求使用者必須在該對話框完成選擇才能繼續下去,結果可以透過Form.DialogResult傳回。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
 
namespace WinLab.ResInside
{
    public partial class Agreement : Form
    {
        public Agreement()
        {
            InitializeComponent();
            //載入Agreement.rtf
            Assembly asm = Assembly.GetExecutingAssembly();
            //記得Resource名稱要包含Namespace
            Stream stm = asm.GetManifestResourceStream(
                "WinLab.ResInside.Agreement.rtf");
            richTextBox1.LoadFile(stm, RichTextBoxStreamType.RichText);
            stm.Close();
            //設為唯讀
            richTextBox1.ReadOnly = true;
            this.StartPosition = FormStartPosition.CenterScreen;
        }
 
        private void cbxRead_CheckedChanged(object sender, EventArgs e)
        {
            //勾選己閱讀後才可以按接受鈕
            if (cbxRead.Checked)
                btnOK.Enabled = true;
        }
 
        private void btnOK_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Yes;
        }
 
        private void btnNO_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.No;
        }
 
        
    }
}

觸發顯示授權書的Code也很簡單,兩三行就可以打發。

    ResInside.Agreement agr = 
        new WinLab.ResInside.Agreement();
    //不接受就不准玩
    if (agr.ShowDialog() != DialogResult.Yes)
        this.Close();

Comments

Be the first to post a comment

Post a comment