博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

winform 异步添加文本提示

Posted on 2016-11-08 18:11  system_kk  阅读(230)  评论(0编辑  收藏  举报

后台代码:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Windows.Forms;
 9 using System.Threading;
10 
11 namespace winform
12 {
13     public partial class Form2 : Form
14     {
15         public Form2()
16         {
17             InitializeComponent();
18         }
19         //创建一个委托,是为访问TextBox控件服务的。
20         public delegate void UpdateTxt(string msg);
21         //定义一个委托变量
22         public UpdateTxt updateTxt;
23 
24         //修改TextBox值的方法。
25         public void UpdateTxtMethod(string msg)
26         {
27             richTextBox1.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")+":"+ msg + "\r\n");
28             richTextBox1.ScrollToCaret();
29         }
30 
31         //此为在非创建线程中的调用方法,其实是使用TextBox的Invoke方法。
32         public void ThreadMethodTxt(int n)
33         {
34             this.BeginInvoke(updateTxt, "线程开始执行,执行" + n + "次,每一秒执行一次");
35             for (int i = 0; i < n; i++)
36             {
37                 this.BeginInvoke(updateTxt, i.ToString());
38                 //一秒 执行一次
39                 Thread.Sleep(1000);
40             }
41             this.BeginInvoke(updateTxt, "线程结束");
42         }
43         //开启线程
44         private void button1_Click(object sender, EventArgs e)
45         {
46             Thread objThread = new Thread(new ThreadStart(delegate
47             {
48                 ThreadMethodTxt(Convert.ToInt32(textBox1.Text.Trim()));
49             }));
50             objThread.Start();
51         }
52 
53         private void ShowMsg(string str)
54         {
55             if (updateTxt == null)
56                 updateTxt = new UpdateTxt(UpdateTxtMethod);
57             this.BeginInvoke(updateTxt, str);
58         }
59 
60         private void Form1_Load_1(object sender, EventArgs e)
61         {
62             //实例化委托
63             updateTxt = new UpdateTxt(UpdateTxtMethod);
64             richTextBox1.Anchor = AnchorStyles.None;
65         }
66 
67         private void button2_Click(object sender, EventArgs e)
68         {
69             ShowMsg("1");
70         }
71     }
72 }
View Code

效果: 

参考:http://www.sufeinet.com/thread-3556-1-1.html

 

其他代码

  private void ShowMsg(string str)
        {
            this.BeginInvoke(new Action(() =>
            {
                richTextBox1.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + ":" + str + "\r\n");
                richTextBox1.ScrollToCaret();
            }));

            //this.BeginInvoke(new Action(delegate()
            //    {
            //        richTextBox1.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + ":" + str + "\r\n");
            //        richTextBox1.ScrollToCaret();
            //    }));

            //this.BeginInvoke(new Action<string>((msg) =>
            //{
            //    richTextBox1.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + ":" + msg + "\r\n");
            //    richTextBox1.ScrollToCaret();
            //}), str);
        }
View Code

 

工具类:

public class MsgLog
    {
        public event EventHandler InfoHandle;
        public event EventHandler ErrHandle;
        public event EventHandler ClearHandle;
        public class LogArgs : EventArgs
        {
            public string txt { get; set; }
        }

        public void Info(string msg)
        {
            LogArgs args = new LogArgs();
            args.txt = msg;
            OnInfo(args);
        }

        public void Err(string msg)
        {
            LogArgs args = new LogArgs();
            args.txt = msg;
            OnErr(args);
        }

        public void Clear()
        {
            LogArgs args = new LogArgs();
            OnClear(args);
        }

        private void OnInfo(LogArgs args)
        {
            InfoHandle(this, args);
        }

        private void OnErr(LogArgs args)
        {
            ErrHandle(this, args);
        }

        private void OnClear(LogArgs args)
        {
            ClearHandle(this, args);
        }
    }
View Code

初始化

public partial class LY_SJH : Form
    {
        private MsgLog log = new MsgLog();
        ////这里在窗体上没有拖拽一个NotifyIcon控件,而是在这里定义了一个变量  
        private NotifyIcon notifyIcon = null;
        public LY_SJH()
        {
            InitializeComponent();
            InitialTray();
        }

        private void LY_TRQ_Load(object sender, EventArgs e)
        {
            log.InfoHandle += delegate (object o, EventArgs arg)
            {
                txtInfoLog.Invoke((MethodInvoker)delegate
                {
                    MsgLog.LogArgs args = (MsgLog.LogArgs)arg;
                    txtInfoLog.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + args.txt + "\r\n");
                    LogUtils.Info(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + args.txt);
                    txtInfoLog.ScrollToCaret();
                });
            };

            log.ErrHandle += delegate (object o, EventArgs arg)
            {
                txtErrLog.Invoke((MethodInvoker)delegate
                {
                    MsgLog.LogArgs args = (MsgLog.LogArgs)arg;
                    txtErrLog.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + args.txt + "\r\n");
                    txtErrLog.ScrollToCaret();
                });
            };

            log.ClearHandle += delegate (object o, EventArgs arg)
            {
                txtInfoLog.Invoke((MethodInvoker)delegate
                {
                    txtInfoLog.Text = "";
                });

                txtErrLog.Invoke((MethodInvoker)delegate
                {
                    txtErrLog.Text = "";
                });
            };

            ThreadPool.QueueUserWorkItem(new WaitCallback(ClearMessage));

            try
            {
                 
                //SetAutoRun();//每次打开强制设置 自启动
                //menuAutoRun.Enabled = false;
                CheckAutoRun();
                AutoRun();
            }
            catch (Exception ex)
            {
                log.Err("出错=" + ex.Message);
            }
        }

        private void ClearMessage(object obj)
        {
            while (true)
            {
                log.Clear();
                Thread.Sleep(1000 * 60 * 60 * 24 * 7);
            }
        }

        private void LY_TRQ_FormClosing(object sender, FormClosingEventArgs e)
        {

            LogUtils.Debug("==程序关闭(最小化至托盘==");
            //System.Environment.Exit(System.Environment.ExitCode);
            e.Cancel = true;
            //通过这里可以看出,这里的关闭其实不是真正意义上的“关闭”,而是将窗体隐藏,实现一个“伪关闭”  
            this.Hide();
        }

        private void LY_TRQ_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (e.CloseReason == CloseReason.WindowsShutDown)
            {
                //添加所需使用的代码
                LogUtils.Debug(DateTime.Now + "【电脑关机或者被注销" + "===系统用户:" + System.Environment.UserName + "");
            }
            if (e.CloseReason == CloseReason.TaskManagerClosing)
            {
                //添加所需使用的代码
                LogUtils.Debug(DateTime.Now + "【任务管理器关闭" + "===系统用户:" + System.Environment.UserName + "");
            }
            if (e.CloseReason == CloseReason.None)
            {
                //添加所需使用的代码
                LogUtils.Debug(DateTime.Now + "【未知意外关闭" + "===系统用户:" + System.Environment.UserName + "");
            }
        }

         

        private void btnstart_Click(object sender, EventArgs e)
        {
            //StartDoWork();
        }
        

        private void btnstop_Click(object sender, EventArgs e)
        {
            List<string> txts = new List<string>();
            if (chkSJH_Bottle.Checked)
            {
                QuartzUtil.DeleteJob("Job_SJHhandler_DoBottleWork");
                txts.Add(chkSJH_Bottle.Text.Trim());
            }
            if (chkSJH_AfterCheck.Checked)
            {
                QuartzUtil.DeleteJob("Job_SJHhandler_DoAfterCheck");
                txts.Add(chkSJH_AfterCheck.Text.Trim());
            }

            if (txts.Count > 0)
            {
                btnstart.Text = "启 动";
                btnstart.Enabled = true;

                log.Info("暂停...(" + string.Join(",", txts));
            }
            else
            {
                log.Info("请选择要暂停的任务");
            }
        }
        private void btnClearLog_Click(object sender, EventArgs e)
        {
            log.Clear();
            log.Info("清空日志");
        }


        private void InitialTray()
        {
            #region notifyIcon
            //隐藏主窗体  
            this.Hide();

            //实例化一个NotifyIcon对象  
            notifyIcon = new NotifyIcon();
            //托盘图标气泡显示的内容  
            notifyIcon.BalloonTipText = "正在后台运行";
            //托盘图标显示的内容  
            notifyIcon.Text = "窗体托盘后台运行中";
            //注意:下面的路径可以是绝对路径、相对路径。但是需要注意的是:文件必须是一个.ico格式  
            string str = System.Windows.Forms.Application.StartupPath;
            notifyIcon.Icon = new System.Drawing.Icon(str + "/logo.ico");  //图标 必填

            //true表示在托盘区可见,false表示在托盘区不可见  
            notifyIcon.Visible = true;
            //气泡显示的时间(单位是毫秒)  
            notifyIcon.ShowBalloonTip(3000);
            notifyIcon.MouseClick += new System.Windows.Forms.MouseEventHandler(notifyIcon_MouseClick);

            //帮助选项,这里只是“有名无实”在菜单上只是显示,单击没有效果,可以参照下面的“退出菜单”实现单击事件  
            MenuItem help = new MenuItem("帮助");
            help.Click += new EventHandler(help_Click);
            //关于选项  
            MenuItem about = new MenuItem("关于");
            about.Click += new EventHandler(about_Click);
            //退出菜单项  
            MenuItem exit = new MenuItem("退出");
            exit.Click += new EventHandler(exit_Click);

            ////关联托盘控件  
            MenuItem[] childen = new MenuItem[] { help, about, exit };
            notifyIcon.ContextMenu = new ContextMenu(childen);

            //this.ShowInTaskbar = true;
            //窗体关闭时触发  
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.LY_TRQ_FormClosing);

            #endregion 
        }


        private void menuAutoRun_Click(object sender, EventArgs e)
        {
            SetAutoRun();
        }

        #region 私有辅助方法(自启动
        /// <summary>
        /// 检查是否开机启动,并设置控件状态
        /// </summary>
        private void CheckAutoRun()
        {
            string strFilePath = Application.ExecutablePath;
            string strFileName = System.IO.Path.GetFileName(strFilePath);

            if (SystemHelper.IsAutoRun(strFilePath + " -autorunSJH", strFileName + " -autorunSJH"))
            {
                menuAutoRun.Checked = true;
            }
            else
            {
                menuAutoRun.Checked = false;
            }
        }

        private void AutoRun()
        {
            if (menuAutoRun.Checked)
            {

                string[] strArgs = Environment.GetCommandLineArgs();
                log.Info("启动运行...(" + string.Join(",", strArgs));
                LogUtils.Info("启动运行...(" + string.Join(",", strArgs));


                if (strArgs.Length >= 2 && strArgs[1].Equals("-autorunSJH"))
                {
                    log.Info("我是开机自启动运行...");
                    LogUtils.Info("我是开机自启动运行...");
                    StartDoWork();//开始干活
                }
            }
        }

        /// <summary>
        /// 设置程序开机自启动
        /// </summary>
        private void SetAutoRun()
        {
            string strFilePath = Application.ExecutablePath;
            string strFileName = System.IO.Path.GetFileName(strFilePath);

            try
            {
                SystemHelper.SetAutoRun(strFilePath + " -autorunSJH", strFileName + " -autorunSJH", !menuAutoRun.Checked);
                menuAutoRun.Checked = !menuAutoRun.Checked;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region 关闭最小化

        /// <summary>  
        /// 鼠标单击  
        /// </summary>  
        /// <param name="sender"></param>  
        /// <param name="e"></param>  
        private void notifyIcon_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            //鼠标左键单击  
            if (e.Button == MouseButtons.Left)
            {
                //如果窗体是可见的,那么鼠标左击托盘区图标后,窗体为不可见  
                if (this.Visible == true)
                {
                    this.Visible = false;
                }
                else
                {
                    this.Visible = true;
                    this.Activate();
                }
            }
        }

        /// <summary>  
        /// 退出选项  
        /// </summary>  
        /// <param name="sender"></param>  
        /// <param name="e"></param>  
        private void exit_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("你确定要退出终端服务程序吗?", "确认", MessageBoxButtons.OKCancel,
  MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
            {
                notifyIcon.Visible = false;
                this.Close();
                this.Dispose();
                //Application.Exit();
                System.Environment.Exit(System.Environment.ExitCode);
                LogUtils.Info("退出终端服务程序");
            }
        }

        /// <summary>  
        /// 关于选项  
        /// </summary>  
        /// <param name="sender"></param>  
        /// <param name="e"></param>  
        private void about_Click(object sender, EventArgs e)
        {
            MessageBox.Show("===By xx技术===");
        }
        /// <summary>  
        /// 帮助选项  
        /// </summary>  
        /// <param name="sender"></param>  
        /// <param name="e"></param>  
        private void help_Click(object sender, EventArgs e)
        {
            MessageBox.Show("===详情请联系QQ:1435920942===");
        }



        #endregion
    }
View Code