线程对话框基类

打开对话框处理一些耗时任务时,需要实时显示处理进度,每次设计线程、主线程消息通讯和界面刷新都比较烦,因此设计一个基类。

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Diagnostics;
using System.Drawing;

public class BaseForm : Form
    {
        public delegate void OutputMsgEventHandle(ThreadOutputMsg msg);
        public event OutputMsgEventHandle OutputtedMsg;

        private SynchronizationContext _mainSynContext = null;
        private ThreadOutputMsg _msg = null;

        private void InitializeComponent()
        {
            this.SuspendLayout();
            // 
            // BaseForm
            // 
            this.ClientSize = new System.Drawing.Size(284, 261);
            this.Name = "BaseForm";
            this.ResumeLayout(false);
        }

        public BaseForm()
        {
            this.Load += new EventHandler(BaseForm_Load);
        }

        public Thread StartThread(ParameterizedThreadStart start, object parameter, OutputMsgEventHandle msgEnvent)
        {
            _mainSynContext = SynchronizationContext.Current;
            if (_msg == null)
                _msg = new ThreadOutputMsg();
            //移除其他添加的事件
            if (OutputtedMsg != null)
            {
                Delegate[] deles = OutputtedMsg.GetInvocationList();
                foreach (Delegate dele in deles)
                {
                    OutputtedMsg -= dele as OutputMsgEventHandle;
                }
            }
            if (msgEnvent != null)
                OutputtedMsg = msgEnvent;
            //开启线程
            Thread thread = new Thread(start);
            if (parameter == null)
                thread.Start();
            else
                thread.Start(parameter);

            return thread;
        }

        /// <summary>
        /// 线程内部调用,发送消息到主线程,这样就保证了OutputtedMsg事件肯定在主线程中执行
        /// </summary>
        public virtual void OutputThreadMsg(int cur, int count, string msg, ThreadOutputMsgType msgType, object param = null)
        {
            if (OutputtedMsg == null || _mainSynContext == null) return;
            if (_msg == null)
                _msg = new ThreadOutputMsg();
            _msg.Current = cur;
            _msg.Count = count;
            _msg.Message = msg;
            _msg.MsgType = msgType;
            _msg.Param = param;
            _mainSynContext.Send(new SendOrPostCallback(SendMessage_Callback), _msg);
        }
        /// <summary>
        /// 线程内部调用,发送消息到主线程,这样就保证了OutputtedMsg事件肯定在主线程中执行
        /// </summary>
        public virtual void OutputThreadMsg(ThreadOutputMsg msg)
        {
            if (OutputtedMsg == null || _mainSynContext == null) return;
            _mainSynContext.Send(new SendOrPostCallback(SendMessage_Callback), msg);
        }
        /// <summary>
        /// 主线程的同步对象SynchronizationContext.Send调用,这个是在主线程中执行的
        /// </summary>
        public virtual void SendMessage_Callback(object obj)
        {
            if (OutputtedMsg != null)
                OutputtedMsg(obj as ThreadOutputMsg);
        }

        /// <summary>
        /// 获取所有子文件,输出全路径
        /// </summary>
        /// <param name="prjPath">待分析目录</param>
        /// <param name="filter">过滤后缀,默认".csproj",多个用英文';'隔开,后缀前的'.'不能省略</param>
        /// <param name="files">输出的文件全路径列表</param>
        public void GetAllChildFiles(string destPath, ref List<string> files, string filter = null)
        {
            if (files == null) return;
            //获取文件夹信息
            DirectoryInfo folder = new DirectoryInfo(destPath);
            if (!folder.Exists)
                return;

            //分析过滤后缀
            bool bAll = false;
            if (string.IsNullOrWhiteSpace(filter) || filter == "*.*")
                bAll = true;
            else
            {
                filter = filter.Replace(" ", "");
                filter = filter.Replace("*", "");
                if (string.IsNullOrWhiteSpace(filter) || filter == ".")
                    bAll = true;
                else
                {
                    if (filter.Substring(filter.Length - 1) != ";")
                        filter += ";";
                    filter = filter.ToLower();
                }
            }

            //遍历文件
            foreach (FileInfo file in folder.GetFiles())
            {
                //不遍历隐藏文件
                if ((file.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
                    continue;
                if (bAll)
                    files.Add(file.FullName);
                else if (string.IsNullOrWhiteSpace(file.Extension))
                    continue;
                else if (filter.IndexOf(file.Extension.ToLower() + ";") != -1 && file.FullName.IndexOf("DevExpress") == -1)
                    files.Add(file.FullName);
            }
            
            //遍历文件夹
            foreach (DirectoryInfo child in folder.GetDirectories())
            {
                //不遍历隐藏文件夹
                if ((child.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
                    continue;
                GetAllChildFiles(child.FullName, ref files, filter);
            }
        }

        public void GetAllChildFiles(string destPath, ref List<string> files, ref List<string> folders)
        {
            if (files == null || folders == null) return;
            //获取文件夹信息
            DirectoryInfo folder = new DirectoryInfo(destPath);
            if (!folder.Exists)
                return;

            //遍历文件
            foreach (FileInfo file in folder.GetFiles())
            {
                files.Add(file.FullName);
            }

            //遍历文件夹
            foreach (DirectoryInfo child in folder.GetDirectories())
            {
                folders.Add(child.FullName);
                GetAllChildFiles(child.FullName, ref files, ref folders);
            }
        }

        /// <summary>
        /// 完全退出程序
        /// </summary>
        public void ExistApplication()
        {
            Process.GetCurrentProcess().Kill();
        }

        private void BaseForm_Load(object sender, EventArgs e)
        {
            if (DesignMode) return;

            Button btnExit = new Button();
            btnExit.Text = "退出";
            btnExit.Location = new Point(this.Width - 16 + 1 - 37, -1);//可根据情况自由选择位置或设置为变量
            btnExit.Size = new Size(37, 20);
            btnExit.Click += new EventHandler(BtnExit_Click);
            this.Controls.Add(btnExit);
            btnExit.BringToFront();
            btnExit.TabStop = false;
        }

        private void BtnExit_Click(object sender, EventArgs e)
        {
            ExistApplication();
        }
    }

    public class ThreadOutputMsg
    {
        public int Current { get; set; }
        public int Count { get; set; }
        public string Message { get; set; }
        public ThreadOutputMsgType MsgType { get; set; }
        /// <summary>
        /// 额外参数,由用户自定义
        /// </summary>
        public object Param { get; set; }
    }

    public enum ThreadOutputMsgType { Error, Succeed, Normal}
原文地址:https://www.cnblogs.com/publiter/p/13495876.html