• winfrom C#树勾选等


    AfterCheck

            /// <summary>
            /// 树勾选
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void tvCourse_AfterCheck(object sender, TreeViewEventArgs e)
            {
                if (e.Action ==TreeViewAction.ByMouse)
                {
                    if (e.Node.Checked)
                    {
                        SetChildNode(e.Node, true);
                        if (null!= e.Node.Parent)
                        {
                            SetParentNode(e.Node, true);
                        }
                        //获取选中节点值
                        lstChapterIds.Add(e.Node.Name);
                        this.btnDelRes.Enabled = true;
                    }
                    else
                    {
                        //取消节点选中状态之后,取消所有父节点的选中状态
                        SetChildNode(e.Node, false);
                        //如果节点存在父节点,取消父节点的选中状态
                        if (e.Node.Parent != null)
                        {
                            SetParentNode(e.Node, false);
                        }
                        //获取选中节点值
                        if (lstChapterIds.Contains(e.Node.Name))
                        {
                            lstChapterIds.Remove(e.Node.Name);
                            if (!lstChapterIds.Any())
                            {
                                this.btnDelRes.Enabled = false;
                            }
                        }
                    }
                    
                }
            }
    AfterCheck

    设置节点

            /// <summary>
            /// 查找根节点
            /// </summary>
            /// <param name="node">节点node</param>
            /// <returns></returns>
            private TreeNode FindParentNode(TreeNode node)
            {
                if (node.Parent == null)
                {
                    return node;
                }
                else
                {
                    return FindParentNode(node);
                }
            }
    
            /// <summary>
            /// 设置父节点
            /// </summary>
            /// <param name="node">当前节点</param>
            /// <param name="state">状态</param>
            private void SetParentNode(TreeNode node, bool state)
            {
                TreeNode pNode = node.Parent;
                if (null != pNode)
                {
                    pNode.Checked = state;
                    bool flag = false;
                    foreach (TreeNode currNode in pNode.Nodes)
                    {
                        if (!currNode.Checked)  //控制父节点全选,父节点选中去掉!
                        {
                            flag = false;
                            pNode.Checked = flag;
                            break;
                        }
                        //SetParentNode(item, state);
                    }
                    if (pNode.Checked )
                    {
                        //获取选中节点值
                        lstChapterIds.Add(pNode.Name);
                    }
                    else
                    {
                        if (lstChapterIds.Contains(pNode.Name))
                        {
                            lstChapterIds.Remove(pNode.Name);
                        }
                    }
                    SetParentNode(pNode, flag);
                    
                }
            }
            /// <summary>
            /// 设置子节点
            /// </summary>
            /// <param name="node">当前节点</param>
            /// <param name="state">状态</param>
            private void SetChildNode(TreeNode node, bool state)
            {
                TreeNodeCollection tncNodes = node.Nodes;
                if (tncNodes.Count>0)
                {
                    foreach (TreeNode currNode in tncNodes)
                    {
                        currNode.Checked = state;
                        if (currNode.Checked)
                        {
                            //获取选中节点值
                            lstChapterIds.Add(currNode.Name);
                        }
                        else
                        {
                            if (lstChapterIds.Contains(currNode.Name))
                            {
                                lstChapterIds.Remove(currNode.Name);
                            }
                        }
    
                        SetChildNode(currNode, state);
                    }
                }
            }
    View Code

    程序只开一个:program.cs

    bool createdNew = false;
                System.Threading.Mutex instance = new System.Threading.Mutex(true, Application.ProductName, out createdNew);
                if (createdNew)
                {
                    //...........code
                    instance.ReleaseMutex();
                }
                else
                {
                    MessageBox.Show("该程序已经在运行!", Application.ProductName,MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    Application.Exit();
                }      
    View Code

    委托 不同线程间访问控件

    private delegate void UploadPro(int mProgre);
    
    private event UploadPro UploadProEvent;
    
    UploadProEvent +=ResourceManage_UploadProEvent;
    
    void ResourceManage_UploadProEvent(int mProgree)
    {
    
      //......
    
    }
    
    var thread = new Thread(new ThreadStart(method));
    thread.Start();
    View Code

    this.Invoke(UploadProEvent,currentPro);

    解压缩 文件

    ZipInputStream inputStream = new ZipInputStream(File.OpenRead(strFilePath));
    ZipEntry theEntry;
    //读取文件名
                            List<string> fileNameList = new List<string>();
                            while ((theEntry = inputStream.GetNextEntry()) != null)
                            {
                                totalSize += theEntry.UncompressedSize;
                                string templateName = theEntry.FileName;
                                string fileName = Path.GetFileName(templateName);
                                if (!string.IsNullOrEmpty(fileName))
                                    fileNameList.Add(fileName);
                            }
                            inputStream.Close();
    
    
     #region 解压文件
    
                    inputStream = new ZipInputStream(File.OpenRead(filePath));
                    //long totalSize = inputStream.Length;
                    long currentSize = 0;
                    int currentPro = 0;
                    ZipEntry theEntry;
                    ZipFile zf = ZipFile.Read(filePath);
                    //以文件流来解压所有文件,同时计算进度
                    while ((theEntry = inputStream.GetNextEntry()) != null)
                    {
                        //totalSize += theEntry.UncompressedSize;
                        //long totalSize = theEntry.UncompressedSize;
                        //destPath += "/";
                        //string templateName = theEntry.FileName;
                        //string fileName = Path.GetFileName(templateName);
                        ////string dir = Path.GetDirectoryName(templateName);
                        //string dir = templateName;
                        //if (!dir.Contains("\") && string.IsNullOrEmpty(fileName))
                        //{
                        //    continue;
                        //} 
                        ////截取目录文件夹
                        //if (dir.Contains("\"))
                        //    dir = dir.Substring(dir.IndexOf("\") + 1, dir.Length - dir.IndexOf("\") - 1);
    
                        //if (templateName.Length == (dir + "/" + fileName).Length) dir = "";
    
                        
                        ////theEntry.IsDirectory 是否目录
    
                        //string path = Path.GetDirectoryName(destPath) + "/" + dir + "/";
                        ////Path.GetDirectoryName(baseDir) + "/";//
                        //if (!Directory.Exists(path)) 
                        //    Directory.CreateDirectory(path);
    
                        string strFilePath = string.Empty;
                        string templateName = theEntry.FileName;
                        if (!templateName.Contains("\"))
                        {
                            //文件
                            strFilePath = destPath + "\" + theEntry.FileName;
                        }
                        else
                        {
                            //文件夹里文件
                            strFilePath = destPath + theEntry.FileName;
                        }
                        if (!Directory.Exists(Path.GetDirectoryName(strFilePath)))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(strFilePath));
                        }
                        string fileName = Path.GetFileName(templateName);
                        if (fileName != String.Empty)
                        {
                            FileStream streamWriter = File.OpenWrite(strFilePath); //解压文件到指定的目录 
                            int size = 0;
                            byte[] data = new byte[2048];
                            try
                            {
                                while (true)
                                {
                                    size = inputStream.Read(data, 0, data.Length);
                                    if (size > 0)
                                    {
                                        streamWriter.Write(data, 0, size);
                                        currentSize += size;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                    currentPro = Convert.ToInt32(100 * currentSize / totalSize);
    
                                    this.Invoke(UploadProEvent,currentPro);
    
                                }
                            }
                            catch (Exception ex)
                            {
                                LogHelper.Error(this.GetType(), ex);
                                this.Invoke(UploadProEvent, -1);    //-1 导入失败
                            }
                            finally
                            {
                                streamWriter.Close();
                            }
                        }
    
     
                    }
                    inputStream.Close();
    
                    #endregion
    View Code

    检查指导文件盘符,获取空间大盘符

            /// <summary>
            /// 检查指导盘符剩余空间
            /// </summary>
            /// <param name="str_HardDiskName"></param>
            /// <returns></returns>
            public static long GetHardDiskFreeSpace(string str_HardDiskName)
            {
                if (string.IsNullOrEmpty(str_HardDiskName)) return 0;
    
                long freeSpace = new long();
                System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();
                foreach (System.IO.DriveInfo drive in drives)
                {
                    if (drive.Name == str_HardDiskName)
                    {
                        freeSpace = drive.TotalFreeSpace;
                    }
                }
                return freeSpace;
            }
    
            /// <summary>
            /// 找出当前客户端剩余空间最大盘符
            /// </summary>
            /// <returns></returns>
            public static Dictionary<string, long> GetSystemDirtory()
            {
                Dictionary<string, long> freeSpace = new Dictionary<string, long>();
                DriveInfo[] drives = DriveInfo.GetDrives();
                foreach (DriveInfo drive in drives)
                {
                    if (drive.DriveType == DriveType.Fixed)
                        freeSpace.Add(drive.Name, drive.TotalFreeSpace);
                }
    
                string hardDiskName = freeSpace.ToArray().Max(x => x.Key);
                long hardDiskSize = freeSpace.ToArray().Max(x => x.Value);
    
                freeSpace.Clear();
                freeSpace.Add(hardDiskName, hardDiskSize);
    
                return freeSpace;
            }
    View Code

    获取MAC地址

    /// <summary>
            /// 获取网卡MAC地址
            /// </summary>
            /// <returns></returns>
            public static string GetNetCardMAC()
            {
                try
                {
                    string stringMAC = "";
                    ManagementClass MC = new ManagementClass("Win32_NetworkAdapterConfiguration");
                    ManagementObjectCollection MOC = MC.GetInstances();
                    foreach (ManagementObject MO in MOC)
                    {
                        if ((bool)MO["IPEnabled"] == true)
                        {
                            stringMAC += MO["MACAddress"].ToString();
    
                        }
                    }
                    return stringMAC;
                }
                catch
                {
                    return "";
                }
            }
    View Code

    获取远程文件信息

            /// <summary>
            /// 获取远程文件信息
            /// </summary>
            /// <param name="url"></param>
            /// <returns></returns>
            public static RemoteFileInfo GetFileInfo(string url)
            {
                RemoteFileInfo result = new RemoteFileInfo();
    
                try
                {
                    GC.Collect();
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    result.MimeType = response.ContentType;
                    result.LastModified = response.LastModified;
                    result.FileSize = response.ContentLength;
                    result.AcceptRanges = String.Compare(response.Headers["Accept-Ranges"], "bytes", true) == 0;
    
                    //关闭连接
                    response.Close();
                    request.KeepAlive = false;
                }
                catch (Exception ex)
                {
                    throw;
                }
    
                return result;
            }
    View Code

    错误日志

           #region 日志方法
           public void LogTest(string str)
           {
               string path = System.IO.Directory.GetCurrentDirectory() + "\log\";
               if (!Directory.Exists(path))
               {
                   DirectoryInfo directorylnfo = new DirectoryInfo(path);
                   directorylnfo.Create();
               }
               string dt = "
    时间:" + DateTime.Now.ToString("yyyymmddhhmmss") + "
    内容:" + str;
               int len = dt.Length;
               byte[] inputByts = new byte[len];
               inputByts = Encoding.GetEncoding("utf-8").GetBytes(dt);
               System.IO.FileStream fs = new System.IO.FileStream(path + "log.txt", System.IO.FileMode.OpenOrCreate);
               fs.Seek(0, System.IO.SeekOrigin.End);
               fs.Write(inputByts, 0, inputByts.Length);
               fs.Close();//关闭流
           } 
           #endregion
    View Code
            /// <summary>
            /// 错误日志
            /// </summary>
            /// <param name="errorMsg"></param>
            public static void WriteLog(Exception ex)
            {
                string logPath = GetResDir() + "/log";
                string message = string.Format("
    
    异常时间:{0} 
    错误源:{1} 
    异常信息:{2}",
                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss,fff"), ex.Source, ex.Message);
                File.AppendAllText(logPath + DateTime.Now.ToString("yyyy.MM.dd") + ".log", message, Encoding.UTF8);
            }
    View Code

    启动停止服务

    /// <summary>
            /// 启动服务sc.DisplayName
            /// </summary>
            /// <param name="serverName"></param>
            public static void StartService(string serverName)
            {
                if (string.IsNullOrEmpty(serverName)) return;
                ServiceController sc = new ServiceController(serverName);
                if (sc.DisplayName != null)
                {
                    if (sc.Status == ServiceControllerStatus.Stopped) sc.Start();
                }
            }
    
            /// <summary>
            /// 停止服务
            /// </summary>
            /// <param name="serverName"></param>
            public static void StopService(string serverName)
            {
                if (string.IsNullOrEmpty(serverName)) return;
                ServiceController sc = new ServiceController(serverName);
                if (sc.DisplayName != null) {
                    if (sc.Status == ServiceControllerStatus.Running) sc.Stop();
                }
            }
    View Code

    插入修改表数据

           public string InsertORupdateData<T>(List<T> _list, string dtName,string columnName)
           {
               StringBuilder sbInsert = new StringBuilder();
    
               ArrayList list = new ArrayList();
               try
               {
                   string sqlstr = "";
                   if (_list != null && _list.Count > 0)
                   {
    
                       System.Reflection.PropertyInfo[] p = _list[0].GetType().GetProperties();
                       int length = 0;
                       string values = "";
                   
                       for (int i = 0; i < _list.Count; i++)
                       {
                           string sbUpdateSql = "";
                           int count = 0;
                           string upwh = "";
                           length = 0;
                           //通过反射获取list中的字段 
                           foreach (System.Reflection.PropertyInfo pi in p)
                           {
    
                               string cName = pi.Name;
                               string cValue = (pi.GetValue(_list[i], null) == null
                                   ? ""
                                   : (pi.GetValue(_list[i], null)).ToString().Replace("'", ""));    //替换 '语法错误的
    
    
    
                               if (cName.ToLower() == columnName.ToLower())
                               {
                                   string sql = "select count(0) from " + dtName + " where " + columnName + "='"+cValue+"'";
                                   upwh = "  where " + columnName + "='" + cValue + "'";
                                   count = ExcelHelper.GetScalar(sql);
                               }
    
                               if (length == 0)
                               {
                                   sqlstr = "INSERT INTO " + dtName + " (";
                                   values = "(";
                                   sbUpdateSql+="update " + dtName + " set ";
                               }
                               length += 1;
                               if (length < p.Length)
                               {
                                   sbUpdateSql += cName + "= '" + cValue +"',";
                                   sqlstr += cName + ",";
                                   values += "'" + cValue + "',";
                               }
                               else
                               {
                                   sbUpdateSql += cName + "= '" + cValue + "'";
                                   sqlstr += cName + ") Values";
                                   values += "'" + cValue + "');  ";
    
                                   if (count > 0)
                                   {
                                       sqlstr = sbUpdateSql + upwh;
                                       values = "";
                                   }
                               }
                           }
                           sqlstr += values;
                           list.Add(sqlstr);
                       }
                   }
                   //for (int i = 0; i < list.Count; i++)
                   //{
                   //    ArrayList arrList = new ArrayList();
                   //    arrList.Add(list[i]);
                   //    var result = AccessDbHelper.ExecuteSqlTran(arrList);
                   //}
                   //string str = string.Join("", list.ToArray());
                   var result = AccessDbHelper.ExecuteSqlTran(list);
                   return "success";
               }
               catch (Exception err)
               {
                   LogTest(err.ToString());
                   return err.ToString();
               }
    
           }
    View Code
  • 相关阅读:
    getchar,putchar函数
    强制类型转换和整数常量的数据类型及转换
    c语言整型的隐式数据 类型转换
    c语言整型数据输出格式声明
    c语言整型变量的储存空间,以及所表示的整数范围
    c语言常量
    c语言求回文数
    Android4.0源码目录结构详解
    MTK Android源代码目录
    Comparator 和 Comparable
  • 原文地址:https://www.cnblogs.com/love201314/p/6307593.html
Copyright © 2020-2023  润新知