C#軟體開發例項.私人訂製自己的螢幕截圖工具(六)新增配置管理功能

mybwu_com發表於2014-04-25

上一篇:C#軟體開發例項.私人訂製自己的螢幕截圖工具(五)針對拖拽時閃爍卡頓現象的優化

新增設定視窗

在解決方案資源管理器視窗中,右鍵單擊專案名稱,在彈出的選單中選擇:新增》Windows窗體:


輸入窗體名稱“frmSetup”:


設定窗體的Text屬性為“設定”,設定窗體的Size為“472, 276”,StartPosition屬性為“CenterScreen”。

新增設定標籤頁:

左側工具箱》窗器:雙擊“TabControl”


設定的Dock屬性為“Top”,Size屬性為“456, 200”;

新增標籤頁:


新增三個標籤頁,Text分別設定為“基本設定,自動上傳,自動儲存”


新增確定和取消按鈕;

基本設定標籤頁:


從工具箱中新增兩個GroupBox,分別為“熱鍵、截圖選項”;

新增兩個RadioButton,用於熱鍵選擇;

新增四個CheckBox用於截圖選項;

新增兩個TextBox用於設定放大鏡的尺寸;

新增兩個PictureBox用於顯示X和鎖的圖片;

新增圖片資源:

雙擊Properties中的“Resources.resx”


切換到影象檢視:


將圖片複製,貼上到這裡,分別命名為“Lock,X”;

設定PictureBox的Image屬性為對應的資源:


自動上傳標籤頁:


自動儲存標籤頁:


其中檔名稱需要使用兩個ComboBox,Items集合分別設定為:



編寫程式碼:

雙擊設定窗體,切換到程式碼檢視,新增私有變數:

        /// <summary>
        /// 儲存Form1的控制程式碼
        /// </summary>
        private IntPtr frm1Handle = IntPtr.Zero;

修改建構函式:

        /// <summary>
        /// 建構函式
        /// </summary>
        /// <param name="frm1_Handle"></param>
        public frmSetup(IntPtr frm1_Handle)
        {
            InitializeComponent();
            this.frm1Handle = frm1_Handle;
        }

為托盤選單中的設定新增事件處理

開啟主窗體Form1的設計檢視,選中“contextMenuStrip1”


修改設定選單的Name為“tsmi_Set”,雙擊設定選單,新增程式碼:

        /// <summary>
        /// 托盤選單設定事件處理程式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmi_Set_Click(object sender, EventArgs e)
        {
            frmSetup frm = new frmSetup(this.Handle);
            frm.ShowDialog();
        }
編譯,除錯一下,通過托盤圖示的右鍵選單》設定 可以開啟剛剛新增的設定視窗了。

新增專案引用:

主窗體新增相關配置項變數:

        #region 基本設定引數
        /// <summary>
        /// 截圖時是否顯示截圖資訊欄
        /// </summary>
        public bool InfoBoxVisible = true;
        /// <summary>
        /// 截圖時是否顯示編輯工具欄
        /// </summary>
        public bool ToolBoxVisible = true;
        /// <summary>
        /// 截圖中是否包含滑鼠指標形狀
        /// </summary>
        public bool IsCutCursor = true;
        /// <summary>
        /// 截圖時是否顯示放大鏡
        /// </summary>
        public bool ZoomBoxVisible = true;
        /// <summary>
        /// 放大鏡的尺寸——寬度
        /// </summary>
        public int ZoomBoxWidth = 120;
        /// <summary>
        /// 放大鏡的尺寸——高度
        /// </summary>
        public int ZoomBoxHeight = 100;
        #endregion

        #region 圖片上傳引數
        public string PicDescFieldName = "pictitle";
        public string ImageFieldName = "upfile";
        public string PicDesc = "cutImage";
        public string UploadUrl = "http://";
        public bool DoUpload = false;
        #endregion

        #region 自動儲存引數
        /// <summary>
        /// 是否自動儲存到硬碟
        /// </summary>
        public bool AutoSaveToDisk = false;
        /// <summary>
        /// 自動儲存目錄
        /// </summary>
        public string AutoSaveDirectory = string.Empty;
        /// <summary>
        /// 是否啟用日期格式“2013_02_22”的子目錄
        /// </summary>
        public bool AutoSaveSubDir = false;
        /// <summary>
        /// 自動儲存檔名字首
        /// </summary>
        public string AutoSaveFileName1 = "螢幕截圖";
        /// <summary>
        /// 自動檔名規則:日期時間,日期_序號,序號
        /// </summary>
        public string AutoSaveFileName2 = "日期時間";
        /// <summary>
        /// 自動儲存檔案格式:.png, .jpg, .jpeg, .gif, .bmp
        /// </summary>
        public string AutoSaveFileName3 = ".png";
        /// <summary>
        /// 自動儲存檔名序號
        /// </summary>
        public int autoSaveFileIndex = 0;
        #endregion 自動儲存引數

新增“AppSettingKeys”類:

    /// <summary>
    /// 提供配置檔案中AppSettings節中對應的Key名稱
    /// </summary>
    public static class AppSettingKeys
    {
        //基本設定
        public static string HotKeyMode = "HotKeyMode";
        public static string InfoBoxVisible = "InfoBoxVisible";
        public static string ToolBoxVisible = "ToolBoxVisible";
        public static string ZoomBoxVisible = "ZoomBoxVisible";
        public static string ZoomBoxWidth = "ZoomBoxWidth";
        public static string ZoomBoxHeight = "ZoomBoxHeight";
        public static string IsCutCursor = "IsCutCursor";
        //圖片上傳
        public static string PicDescFieldName = "PicDescFieldName";
        public static string ImageFieldName = "ImageFieldName";
        public static string PicDesc = "PicDesc";
        public static string UploadUrl = "UploadUrl";
        public static string DoUpload = "DoUpload";
        //自動儲存
        public static string AutoSaveToDisk = "AutoSaveToDisk";
        public static string AutoSaveSubDir = "AutoSaveSubDir";
        public static string AutoSaveDirectory = "AutoSaveDirectory";
        public static string AutoSaveFileName1 = "AutoSaveFileName1";
        public static string AutoSaveFileName2 = "AutoSaveFileName2";
        public static string AutoSaveFileName3 = "AutoSaveFileName3";

    }

Program.cs檔案新增列舉型別:

    /// <summary>
    /// 控制鍵的型別
    /// </summary>
    public enum KeyModifiers : uint
    {
        None = 0,
        Alt = 1,
        Control = 2,
        Shift = 4,
        Windows = 8
    }

警告:由於xxx是引用封送類的欄位,訪問上面的成員可能導致執行時異常

設定視窗完整程式碼:

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

namespace Screenshot
{
    public partial class frmSetup : Form
    {
        /// <summary>
        /// 儲存Form1的控制程式碼
        /// </summary>
        private IntPtr frm1Handle = IntPtr.Zero;

        /// <summary>
        /// 建構函式
        /// </summary>
        /// <param name="frm1_Handle"></param>
        public frmSetup(IntPtr frm1_Handle)
        {
            InitializeComponent();
            this.frm1Handle = frm1_Handle;
        }

        /// <summary>
        /// 確定按鈕單擊事件處理程式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_ok_Click(object sender, EventArgs e)
        {
            if (checkBox_autoSave.Checked && textBox_saveDir.Text.Trim().Length == 0)
            {
                MessageBox.Show("您選擇了“自動儲存螢幕截圖到磁碟”\n但還沒有設定儲存目錄!");
                return;
            }
            if (checkBox_autoSave.Checked && textBox_saveDir.Text.Trim().Length > 0)
            {
                if (!System.Text.RegularExpressions.Regex.IsMatch(textBox_saveDir.Text.Trim(), "^[a-zA-Z]:\\\\[^/:\\*\\?\"<>\\|]*$", System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                {
                    MessageBox.Show("您選擇了“自動儲存螢幕截圖到磁碟”\n但設定的儲存目錄不是有效的目錄!");
                    return;
                }
                if (!System.IO.Directory.Exists(textBox_saveDir.Text.Trim()))
                {
                    MessageBox.Show("您選擇了“自動儲存螢幕截圖到磁碟”\n但設定的儲存目錄不存在!");
                    return;
                }
            }
            Form1 frm = (Form1)Form.FromHandle(frm1Handle);
            if (frm != null)
            {
                //基本設定
                if (radioButton1.Checked) // && frm.HotKeyMode != 0 無論是否改變都重新註冊熱鍵,解決有時熱鍵失效的問題
                {
                    Form1.UnregisterHotKey(frm1Handle, frm.hotKeyId);
                    Form1.RegisterHotKey(frm1Handle, frm.hotKeyId, (uint)KeyModifiers.Control | (uint)KeyModifiers.Alt, Keys.A);
                    frm.HotKeyMode = 0;
                }

                if (radioButton2.Checked) // && frm.HotKeyMode != 1 無論是否改變都重新註冊熱鍵,解決有時熱鍵失效的問題
                {
                    Form1.UnregisterHotKey(frm1Handle, frm.hotKeyId);
                    Form1.RegisterHotKey(frm1Handle, frm.hotKeyId, (uint)KeyModifiers.Control | (uint)KeyModifiers.Shift, Keys.A);
                    frm.HotKeyMode = 1;
                }

                frm.InfoBoxVisible = ckb_InfoBox.Checked;
                frm.ToolBoxVisible = ckb_ToolBox.Checked;
                frm.IsCutCursor = ckb_CutCursor.Checked;
                frm.ZoomBoxVisible = ckb_ZoomBox.Checked;


                frm.ZoomBoxWidth1 = Convert.ToInt32(tb_zoomBoxWidth.Text);
                frm.ZoomBoxHeight1 = Convert.ToInt32(tb_zoomBoxHeight.Text);

                if (frm.ZoomBoxWidth1 < 120)
                {
                    frm.ZoomBoxWidth1 = 120;
                    tb_zoomBoxWidth.Text = frm.ZoomBoxWidth1.ToString();
                }
                if (frm.ZoomBoxHeight1 < 100)
                {
                    frm.ZoomBoxHeight1 = 100;
                    tb_zoomBoxHeight.Text = frm.ZoomBoxHeight1.ToString();
                }

                //圖片上傳
                frm.PicDescFieldName = textBox_fieldDesc.Text;
                frm.ImageFieldName = textBox_fieldFile.Text;
                frm.PicDesc = textBox_desc.Text;
                frm.UploadUrl = textBox_uploadUrl.Text;
                frm.DoUpload = checkBox_upload.Checked;

                //自動儲存
                frm.AutoSaveToDisk = checkBox_autoSave.Checked;
                frm.AutoSaveSubDir = chb_subDir.Checked;
                frm.AutoSaveDirectory = textBox_saveDir.Text;

                frm.AutoSaveFileName1 = textBox_fileName1.Text;
                if (comboBox_fileName2.SelectedItem != null)
                {
                    frm.AutoSaveFileName2 = comboBox_fileName2.Text;
                }
                else
                {
                    frm.AutoSaveFileName2 = "日期時間";
                }
                if (comboBox_Extn.SelectedItem != null)
                {
                    frm.AutoSaveFileName3 = comboBox_Extn.Text;
                }
                else
                {
                    frm.AutoSaveFileName3 = ".png";
                }
            }

            SaveConfiguration();

            this.Close();
        }

        /// <summary>
        /// 儲存配置資訊到配置檔案
        /// </summary>
        private void SaveConfiguration()
        {
            System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(null);

            //基本設定
            SetConfigAppSetting(ref config, AppSettingKeys.HotKeyMode, radioButton1.Checked ? "1" : "0");
            SetConfigAppSetting(ref config, AppSettingKeys.InfoBoxVisible, ckb_InfoBox.Checked ? "1" : "0");
            SetConfigAppSetting(ref config, AppSettingKeys.ToolBoxVisible, ckb_ToolBox.Checked ? "1" : "0");
            SetConfigAppSetting(ref config, AppSettingKeys.IsCutCursor, ckb_CutCursor.Checked ? "1" : "0");
            SetConfigAppSetting(ref config, AppSettingKeys.ZoomBoxVisible, ckb_ZoomBox.Checked ? "1" : "0");
            SetConfigAppSetting(ref config, AppSettingKeys.ZoomBoxWidth, tb_zoomBoxWidth.Text);
            SetConfigAppSetting(ref config, AppSettingKeys.ZoomBoxHeight, tb_zoomBoxHeight.Text);

            //圖片上傳
            SetConfigAppSetting(ref config, AppSettingKeys.PicDescFieldName, textBox_fieldDesc.Text.Trim());
            SetConfigAppSetting(ref config, AppSettingKeys.ImageFieldName, textBox_fieldFile.Text.Trim());
            SetConfigAppSetting(ref config, AppSettingKeys.PicDesc, textBox_desc.Text.Trim());
            SetConfigAppSetting(ref config, AppSettingKeys.UploadUrl, textBox_uploadUrl.Text.Trim());
            SetConfigAppSetting(ref config, AppSettingKeys.DoUpload, checkBox_upload.Checked ? "1" : "0");

            //自動儲存
            SetConfigAppSetting(ref config, AppSettingKeys.AutoSaveToDisk, checkBox_autoSave.Checked ? "1" : "0");
            SetConfigAppSetting(ref config, AppSettingKeys.AutoSaveSubDir, chb_subDir.Checked ? "1" : "0");
            SetConfigAppSetting(ref config, AppSettingKeys.AutoSaveDirectory, textBox_saveDir.Text.Trim());
            SetConfigAppSetting(ref config, AppSettingKeys.AutoSaveFileName1, textBox_fileName1.Text.Trim());
            if (comboBox_fileName2.SelectedItem != null)
            {
                SetConfigAppSetting(ref config, AppSettingKeys.AutoSaveFileName2, comboBox_fileName2.Text);
            }
            else
            {
                SetConfigAppSetting(ref config, AppSettingKeys.AutoSaveFileName2, "日期時間");
            }
            if (comboBox_Extn.SelectedItem != null)
            {
                SetConfigAppSetting(ref config, AppSettingKeys.AutoSaveFileName3, comboBox_Extn.Text);
            }
            else
            {
                SetConfigAppSetting(ref config, AppSettingKeys.AutoSaveFileName3, ".png");
            }

            config.Save(System.Configuration.ConfigurationSaveMode.Modified);
        }

        /// <summary>
        /// 設定配置資訊
        /// </summary>
        /// <param name="config"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        private bool SetConfigAppSetting(ref System.Configuration.Configuration config, string key, string value)
        {
            try
            {
                if (config.AppSettings.Settings[key] != null)
                {
                    config.AppSettings.Settings[key].Value = value;
                }
                else
                {
                    config.AppSettings.Settings.Add(key, value);
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.Source + ex.StackTrace);
                return false;
            }
        }

        /// <summary>
        /// 獲取配置資訊
        /// </summary>
        /// <param name="config"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        private string GetConfigAppSetting(ref System.Configuration.Configuration config, string key)
        {
            try
            {
                if (config.AppSettings.Settings[key] != null)
                {
                    return config.AppSettings.Settings[key].Value;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.Source + ex.StackTrace);
            }
            return string.Empty;
        }

        /// <summary>
        /// 取消按鈕單擊事件處理程式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        /// <summary>
        /// 視窗載入事件處理程式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmSetup_Load(object sender, EventArgs e)
        {
            chb_subDir.Text = "啟用(按日期命名,格式:" + DateTime.Now.Date.ToString("yyyy_MM_dd") + ")";

            Form1 frm = (Form1)Form.FromHandle(frm1Handle);
            if (frm != null)
            {
                //基本設定
                if (frm.HotKeyMode == 0)
                {
                    radioButton1.Checked = true;
                    radioButton2.Checked = false;
                }
                else
                {
                    radioButton1.Checked = false;
                    radioButton2.Checked = true;
                }

                ckb_InfoBox.Checked = frm.InfoBoxVisible;
                ckb_ToolBox.Checked = frm.ToolBoxVisible;
                ckb_CutCursor.Checked = frm.IsCutCursor;
                ckb_ZoomBox.Checked = frm.ZoomBoxVisible;

                //圖片上傳
                textBox_fieldDesc.Text = frm.PicDescFieldName;
                textBox_fieldFile.Text = frm.ImageFieldName;
                textBox_desc.Text = frm.PicDesc;
                textBox_uploadUrl.Text = frm.UploadUrl;
                checkBox_upload.Checked = frm.DoUpload;

                //自動儲存
                checkBox_autoSave.Checked = frm.AutoSaveToDisk;
                chb_subDir.Checked = frm.AutoSaveSubDir;
                textBox_saveDir.Text = frm.AutoSaveDirectory;
                textBox_fileName1.Text = frm.AutoSaveFileName1;
                comboBox_fileName2.SelectedItem = frm.AutoSaveFileName2;
                comboBox_Extn.SelectedItem = frm.AutoSaveFileName3;


            }
        }
        /// <summary>
        /// 瀏覽按鈕事件處理程式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_browse_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.Description = "請選擇螢幕截圖的儲存目錄:";
            fbd.ShowNewFolderButton = true;
            fbd.RootFolder = Environment.SpecialFolder.MyComputer;
            fbd.SelectedPath = textBox_saveDir.Text;
            if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                textBox_saveDir.Text = fbd.SelectedPath;
            }
        }
        /// <summary>
        /// 更新自動儲存檔名稱示例
        /// </summary>
        private void UpdateFileNameExmple()
        {
            string AutoSaveFileName2 = string.Empty;
            if (comboBox_fileName2.SelectedItem != null)
            {
                AutoSaveFileName2 = comboBox_fileName2.Text;
            }
            string AutoSaveFileName3 = ".png";
            if (comboBox_Extn.SelectedItem != null)
            {
                AutoSaveFileName3 = comboBox_Extn.Text;
            }

            switch (AutoSaveFileName2)
            {
                case "日期_序號":
                    textBox_exmple.Text = textBox_fileName1.Text + DateTime.Now.ToString("yyyy-MM-dd_") + "0001" + AutoSaveFileName3;
                    break;
                case "序號":
                    textBox_exmple.Text = textBox_fileName1.Text + "0001" + AutoSaveFileName3;
                    break;
                default:
                    textBox_exmple.Text = textBox_fileName1.Text + DateTime.Now.ToString("yyyy-MM-dd_HHmmss") + AutoSaveFileName3;
                    break;
            }
        }

        private void comboBox_fileName2_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateFileNameExmple();
        }

        private void comboBox_Extn_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateFileNameExmple();
        }

        private void textBox_fileName1_TextChanged(object sender, EventArgs e)
        {
            UpdateFileNameExmple();
        }

        // Boolean flag used to determine when a character other than a number is entered.
        private bool nonNumberEntered = false;

        private void tb_zoomBoxWidth_KeyDown(object sender, KeyEventArgs e)
        {
            // Initialize the flag to false.
            nonNumberEntered = false;

            // Determine whether the keystroke is a number from the top of the keyboard.
            if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
            {
                // Determine whether the keystroke is a number from the keypad.
                if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
                {
                    // Determine whether the keystroke is a backspace.
                    if (e.KeyCode != Keys.Back)
                    {
                        // A non-numerical keystroke was pressed.
                        // Set the flag to true and evaluate in KeyPress event.
                        nonNumberEntered = true;
                    }
                }
            }
            //If shift key was pressed, it's not a number.
            if (Control.ModifierKeys == Keys.Shift)
            {
                nonNumberEntered = true;
            }
        }

        private void tb_zoomBoxHeight_KeyDown(object sender, KeyEventArgs e)
        {
            // Initialize the flag to false.
            nonNumberEntered = false;

            // Determine whether the keystroke is a number from the top of the keyboard.
            if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
            {
                // Determine whether the keystroke is a number from the keypad.
                if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
                {
                    // Determine whether the keystroke is a backspace.
                    if (e.KeyCode != Keys.Back)
                    {
                        // A non-numerical keystroke was pressed.
                        // Set the flag to true and evaluate in KeyPress event.
                        nonNumberEntered = true;
                    }
                }
            }
            //If shift key was pressed, it's not a number.
            if (Control.ModifierKeys == Keys.Shift)
            {
                nonNumberEntered = true;
            }
        }

        private void tb_zoomBoxWidth_KeyPress(object sender, KeyPressEventArgs e)
        {

            // Check for the flag being set in the KeyDown event.
            if (nonNumberEntered == true)
            {
                // Stop the character from being entered into the control since it is non-numerical.
                e.Handled = true;
            }
        }


        private void tb_zoomBoxHeight_KeyPress(object sender, KeyPressEventArgs e)
        {
            // Check for the flag being set in the KeyDown event.
            if (nonNumberEntered == true)
            {
                // Stop the character from being entered into the control since it is non-numerical.
                e.Handled = true;
            }
        }

        /// <summary>
        /// 放大鏡寬度改變事件處理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tb_zoomBoxWidth_TextChanged(object sender, EventArgs e)
        {
            int zoomWidth = Convert.ToInt32(tb_zoomBoxWidth.Text);
            if (zoomWidth < 120) { zoomWidth = 120; }

            tb_zoomBoxHeight.Text = ((int)(zoomWidth * 100 / 120)).ToString();
        }

        /// <summary>
        /// 放大鏡高度改變事件處理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tb_zoomBoxHeight_TextChanged(object sender, EventArgs e)
        {
            int zoomHeight = Convert.ToInt32(tb_zoomBoxHeight.Text);
            if (zoomHeight < 100) { zoomHeight = 100; }

            tb_zoomBoxWidth.Text = ((int)(zoomHeight * 120 / 100)).ToString();
        }
    }
}

原始碼下載:http://download.csdn.net/detail/testcs_dn/7263143

下一篇:C#軟體開發例項.私人訂製自己的螢幕截圖工具(七)新增放大鏡的功能

相關文章