Chủ Nhật, 26 tháng 4, 2015

[WINFORM] Manual create "File Browse" user control

Create user control can be reuse on another form
File Browse user control function list:
  1. Support choose file using OpenFileDialog
  2. Support save pervious selected file path to INI file
  3. Support custom Filter
  4. Add event ChoosedFile fire after file choosed
  5. Handle event keypress on TextBox file path

Build and view on Toolbox to choose user control display
Drag to Form to use

Config some custom property and event:
  1. Filter property
  2. DefaultPath property
  3. ChoosedFile event
  4. SectionStoreFile
  5. SectionStoreKey

Code:

namespace ReadResourceFile.UserControls
{
    public partial class ucOpenFile : UserControl
    {
        private const string _iniFile = "/Setting.ini";
        [Description("Default file path"), DefaultValue("")]
        public string DefaultPath
        {
            get
            {
                return txtFullPath.Text;
            }
            set
            {
                txtFullPath.Text = value;
            }
        }
 
        private string _sectionStoreFile;
        [DefaultValue("")]
        public string SectionStoreFile
        {
            get { return _sectionStoreFile; }
            set { _sectionStoreFile = value; }
        }
        private string _sectionStoreKey = "FilePath";
        [DefaultValue("FilePath")]
        public string SectionStoreKey
        {
            get { return _sectionStoreKey; }
            set
            {
                if (string.IsNullOrWhiteSpace(value))
                    value = "FilePath";
                _sectionStoreKey = value;
            }
        }
 
        public ucOpenFile()
        {
            InitializeComponent();
        }
 
        public event EventHandler<string> ChoosedFile;
        public void OnChoosedFile(object sender, string arg)
        {
            if (ChoosedFile != null)
                ChoosedFile(sender, arg);
            if (!string.IsNullOrWhiteSpace(SectionStoreFile))
                IniWriter.IniWrite(Environment.CurrentDirectory + _iniFile, SectionStoreFile, SectionStoreKey, arg);
        }
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            if (!string.IsNullOrWhiteSpace(txtFullPath.Text))
            {
                if (File.Exists(txtFullPath.Text))
                    dlg.InitialDirectory = Path.GetDirectoryName(txtFullPath.Text);
                else if (Directory.Exists(txtFullPath.Text))
                    dlg.InitialDirectory = txtFullPath.Text;
                else
                    dlg.InitialDirectory = Path.GetPathRoot(txtFullPath.Text);
            }
            dlg.Filter = Filter;
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                txtFullPath.Text = dlg.FileName;
                OnChoosedFile(txtFullPath, dlg.FileName);
            }
        }
        [Description("Filter file type"), DefaultValue("")]
        public string Filter { getset; }
 
        private void txtFullPath_KeyPress(object sender, KeyPressEventArgs e)
        {
            string path = txtFullPath.Text.Trim();
            if (IsValidPath(path))
            {
                string extension = Path.GetExtension(path).ToLower();
                if (e.KeyChar == (char)13 && File.Exists(path) && (Array.IndexOf(ArrType, ".*">= 0 || Array.IndexOf(ArrType, extension) >= 0))
                {
                    OnChoosedFile(txtFullPath, path);
                }
            }
        }
        private bool IsValidPath(string path)
        {
            if (path.Length < 3)
                return false;
            Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$");
            if (!driveCheck.IsMatch(path.Substring(03))) return false;
            string strTheseAreInvalidFileNameChars = new string(Path.GetInvalidPathChars());
            strTheseAreInvalidFileNameChars += @":/?*" + "\"";
            Regex containsABadCharacter = new Regex("[" + Regex.Escape(strTheseAreInvalidFileNameChars) + "]");
            if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3)))
                return false;
 
            return true;
        }
        public string[] ArrType
        {
            get
            {
                if (string.IsNullOrWhiteSpace(Filter))
                    return new string[0];
                string[] arr = Filter.Split('|');
                string[] output = new string[arr.Length / 2];
                if (arr.Length > 1)
                    for (int i = arr.Length - 1; i >= 0; i -= 2)
                    {
                        if (i % 2 != 0)
                            output[i / 2= arr[i].Trim().Substring(1).ToLower();
                    }
                return output;
            }
        }
 
        private void ucOpenFile_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(SectionStoreFile))
            {
                string filePath = IniWriter.IniRead(Environment.CurrentDirectory + _iniFile, this.SectionStoreFile, SectionStoreKey);
                if (!string.IsNullOrWhiteSpace(filePath))
                    this.DefaultPath = filePath;
            }
        }
 
    }

//IniWriterFile

namespace ReadResourceFile.Code
{
    public class IniWriter
    {
        [DllImport("kernel32")]
        static extern long WritePrivateProfileString(string section, string key,
            string val, string filePath);
        [DllImport("kernel32")]
        static extern int GetPrivateProfileString(string section, string key,
            string def, StringBuilder retVal, int size, string filePath);
 
        public static string IniRead(string strFilePath, string strSection, string strKey)
        {
            var RetVal = new StringBuilder(255);
            GetPrivateProfileString(strSection, strKey, string.Empty, RetVal, 255, strFilePath);
            return RetVal.ToString();
        }
        public static void IniWrite(string strFilePath, string strSection, string strKey, string strValue)
        {
            WritePrivateProfileString(strSection, strKey, strValue, strFilePath);
        }
        public static void IniDeleteKey(string strFilePath, string strSection, string strKey)
        {
            IniWrite(strFilePath, strSection, strKey, null);
        }
        public static void IniDeleteSection(string strFilePath, string strSection)
        {
            IniWrite(strFilePath, strSection, nullnull);
        }
        public static bool KeyExists(string strFilePath, string strSection, string strKey)
        {
            return !string.IsNullOrEmpty(IniRead(strFilePath, strSection, strKey));
        }
    }

Không có nhận xét nào:

Đăng nhận xét