C#

来源:互联网 发布:安卓刷linux系统 编辑:程序博客网 时间:2024/06/14 09:58
这篇文章 主要目的是记录一下 平常用到的一些小方法:

   #region 移除字符串末尾指定字符
        /// <summary>   
        /// 移除字符串末尾指定字符   
        /// </summary>   
        /// <param name="str">需要移除的字符串</param>   
        /// <param name="value">指定字符</param>   
        /// <returns>移除后的字符串</returns>   
        public static string RemoveLastChar(string str, string value)
        {
            int _finded = str.LastIndexOf(value);
            if (_finded != -1)
            {
                return str.Substring(0, _finded);
            }
            return str;
        }
        #endregion

循环关闭窗体:
 foreach (var item in Application.OpenForms)//获取所有打开的窗体
            {
                if (item is SpeakVoicemainFrom)//找到你要关闭的窗体
                {
                    (item as SpeakVoicemainFrom).Close();//关闭改窗体
                    break;
                }

            }

正则匹配姓名:
 public static string GetChineseWords(string oriText)
        {
            string x = @"[\u4E00-\u9FFF]+";
            MatchCollection Matches = Regex.Matches
            (oriText, x, RegexOptions.IgnoreCase);
            StringBuilder sb = new StringBuilder();
            foreach (Match NextMatch in Matches)
            {
                sb.Append(NextMatch.Value);
            }
            return sb.ToString();
        }

   #region 窗体调整大小、按键、菜单事件方法
        /// <summary>
        /// 重写按键监视方法,用于操作窗体
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="keyData"></param>
        /// <returns></returns>
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            int WM_KEYDOWN = 256;
            int WM_SYSKEYDOWN = 260;
            if (msg.Msg == WM_KEYDOWN | msg.Msg == WM_SYSKEYDOWN)
            {
                switch (keyData)
                {
                    case Keys.Escape:
                        //按ESC键后退出对话框
                        if (MessageBox.Show("真的要退出程序吗?", "退出程序", MessageBoxButtons.OKCancel) == DialogResult.OK)
                        {
                            //this.Close();///esc关闭窗体
                            Application.Exit();
                        }
                        break;
                }
            }
            return false;
        }


        const int Guying_HTLEFT = 10;
        const int Guying_HTRIGHT = 11;
        const int Guying_HTTOP = 12;
        const int Guying_HTTOPLEFT = 13;
        const int Guying_HTTOPRIGHT = 14;
        const int Guying_HTBOTTOM = 15;
        const int Guying_HTBOTTOMLEFT = 0x10;
        const int Guying_HTBOTTOMRIGHT = 17;
        /// <summary>
        /// 窗体大小监听事件
        /// </summary>
        /// <param name="m"></param>
        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case 0x0084:
                    base.WndProc(ref m);
                    Point vPoint = new Point((int)m.LParam & 0xFFFF,
                    (int)m.LParam >> 16 & 0xFFFF);
                    vPoint = PointToClient(vPoint);
                    if (vPoint.X <= 5)
                        if (vPoint.Y <= 5)
                            m.Result = (IntPtr)Guying_HTTOPLEFT;
                        else if (vPoint.Y >= ClientSize.Height - 5)
                            m.Result = (IntPtr)Guying_HTBOTTOMLEFT;
                        else m.Result = (IntPtr)Guying_HTLEFT;
                    else if (vPoint.X >= ClientSize.Width - 5)
                        if (vPoint.Y <= 5)
                            m.Result = (IntPtr)Guying_HTTOPRIGHT;
                        else if (vPoint.Y >= ClientSize.Height - 5)
                            m.Result = (IntPtr)Guying_HTBOTTOMRIGHT;
                        else m.Result = (IntPtr)Guying_HTRIGHT;
                    else if (vPoint.Y <= 5)
                        m.Result = (IntPtr)Guying_HTTOP;
                    else if (vPoint.Y >= ClientSize.Height - 5)
                        m.Result = (IntPtr)Guying_HTBOTTOM;
                    break;
                case 0x0201: ///鼠标左键按下的消息
                    m.Msg = 0x00A1; ///更改消息为非客户区按下鼠标
                    m.LParam = IntPtr.Zero; ///默认值
                    m.WParam = new IntPtr(2);///鼠标放在标题栏内
                    base.WndProc(ref m);
                    break;
                default:
                    base.WndProc(ref m);
                    break;
            }
        }
        #endregion

  #region 保存信息到本地配置文件中
        /// <summary>
        /// 保存信息到本地配置文件中
        /// </summary>
        /// <param name="roomId"></param>
        /// <param name="roomName"></param>
        private void SaveConfigSeting(string name, string unitSn)//, string unitSn, string stride
        {
            try
            {
                ExeConfigurationFileMap map = new ExeConfigurationFileMap() { ExeConfigFilename = Environment.CurrentDirectory + @"\TaketheNos.exe.config" };
                Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
                config.AppSettings.Settings["name"].Value = name;
                config.AppSettings.Settings["unitSn"].Value = unitSn;
                // config.AppSettings.Settings["stride"].Value = stride;
                config.Save(ConfigurationSaveMode.Modified);
                System.Configuration.ConfigurationManager.RefreshSection("appSettings");//重新加载新的配置文件
            }
            catch (Exception)
            {
            }
        }
        #endregion


  #region 日志记录
        private static void LogPrint(string log)
        {
            try
            {
                string path = Environment.CurrentDirectory + @"\Logs";
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);
                StreamWriter logSW = new StreamWriter(String.Format(@"{0}\Log_FenZhen{1:yyyyMMdd}.txt", path, DateTime.Now), true);
                logSW.WriteLine(String.Format("{0:yyyy-MM-dd HH:mm:ss}  {1}\n", DateTime.Now, log));


                logSW.Close();
                deleteFilesByTime(path);
            }
            catch
            {


            }
        }
        private static void LogPrints(string log)
        {
            try
            {
                string path = Environment.CurrentDirectory + @"\Logs";
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);
                StreamWriter logSW = new StreamWriter(String.Format(@"{0}\ToUpdate{1:yyyyMMdd}.txt", path, DateTime.Now), true);
                logSW.WriteLine(String.Format("{0:yyyy-MM-dd HH:mm:ss}  {1}\n", DateTime.Now, log));


                logSW.Close();
                deleteFilesByTime(path);
            }
            catch
            {


            }
        }
        /// <summary>
        /// 删除30天后的日志
        /// </summary>
        /// <param name="path"></param>
        public static void deleteFilesByTime(string path)
        {
            Int64 time = 2592000000;//30天的毫秒数
            if (Directory.Exists(path))
            {
                //获取文件夹下所有的文件
                DirectoryInfo dyInfo = new DirectoryInfo(path);
                foreach (FileInfo feInfo in dyInfo.GetFiles())
                {
                    //判断文件日期是否小于定义的日期,是则删除
                    TimeSpan ts = DateTime.Now.Subtract(feInfo.CreationTime);
                    if (ts.TotalMilliseconds > time)
                    {
                        feInfo.Delete();
                    }
                }
            }
        }
        #endregion

希望大家多多给我提意见。


原创粉丝点击