C# winform 代码碎片

 
.BringToFront();
Console.WriteLine("{0},{1},{2}", seccode, loginhash, formhash);
this.Invoke((EventHandler)delegate
{
});
 string[] arg = aaa.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
Thread.Sleep(3000); Application.DoEvents();
 List To ToDataTable
#region [List  ToDataTable ]

        private DataTable ToDataTable<T>(List<T> items)

        {

            var tb = new DataTable(typeof(T).Name);



            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);



            foreach (PropertyInfo prop in props)

            {

                Type t = GetCoreType(prop.PropertyType);

                tb.Columns.Add(prop.Name, t);

            }



            foreach (T item in items)

            {

                var values = new object[props.Length];



                for (int i = 0; i < props.Length; i++)

                {

                    values[i] = props[i].GetValue(item, null);

                }



                tb.Rows.Add(values);

            }



            return tb;

        }
        public static Type GetCoreType(Type t)

        {

            if (t != null && IsNullable(t))

            {

                if (!t.IsValueType)

                {

                    return t;

                }

                else

                {

                    return Nullable.GetUnderlyingType(t);

                }

            }

            else

            {

                return t;

            }

        }
        public static bool IsNullable(Type t)

        {

            return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));

        }


        #endregion
View Code

 扩展

string GetPath(string extension)
{
    var appName = (string)Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(extension).GetValue(null);
    var openWith = (string)Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(appName + @"shellopencommand").GetValue(null);
    var appPath =  System.Text.RegularExpressions.Regex.Match(openWith, "[a-zA-Z0-9:,\\\. ]+").Value.Trim();
    return new FileInfo(appPath).Directory.FullName;
}
GetPath(".rar");
View Code

 注册表

string guid; guid = System.Guid.NewGuid().ToString("N");
            string RegistFileName = "TestSoft";
            RegistryKey key;
            RegistryKey software;
            RegistryKey test;
            RegistryKey Savekey;

            key = Registry.LocalUserhine.OpenSubKey("SOFTWARE", true);
            software = key.CreateSubKey(RegistFileName);
            test = key.OpenSubKey(RegistFileName, true);
            Savekey = test.CreateSubKey("TableTest");
            Savekey.SetValue("User", guid);

            key = Registry.LocalUserhine.OpenSubKey("SOFTWARE", true); 
            test = key.OpenSubKey(RegistFileName, true);
            Savekey = test.OpenSubKey("TableTest", true); 
            guid = (string)Savekey.GetValue("User");
View Code

图片框

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

namespace DemoUI
{
    class PicBox : DevExpress.XtraEditors.PictureEdit
    {
        Color NormalColor = Color.White;
        Color HoverColor = Color.Red;
        Color borderColor = Color.White;
        int borderWidth = 3;

        public PicBox()
        {
            SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            SetStyle(ControlStyles.UserPaint, true);
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            //base.OnPaint(e);
            if (Image != null)
            {

                var rect = new Rectangle(borderWidth / 2, borderWidth / 2, Width - borderWidth, Height - borderWidth);
                var g = e.Graphics;
                //g.Clear(BackColor);
                g.SmoothingMode = SmoothingMode.AntiAlias;
                using (GraphicsPath path = new GraphicsPath())
                {
                    using (Pen pen = new Pen(borderColor, borderWidth))
                    {
                        path.AddEllipse(rect);
                        g.SetClip(path);
                        g.DrawImage(Image, rect);
                        g.ResetClip();
                        g.DrawEllipse(pen, rect);


                    }
                }
            }
            //using (Pen pen = new Pen(Color.White))
            //{
            //    g.DrawRectangle(pen, rect);
            //}
        }

        protected override void OnMouseEnter(EventArgs e)
        {
            base.OnMouseEnter(e);
            borderColor = HoverColor;
            Invalidate();
        }
        protected override void OnMouseLeave(EventArgs e)
        {
            base.OnMouseLeave(e);
            borderColor = NormalColor;
            Invalidate();
        }
    }
}
View Code

 HttpClient TASK

 string uri = url;
                HttpClient client = new HttpClient(); 
                Task<string> task = client.GetStringAsync(uri);
                while (!task.IsCompleted)
                {
                    continue;
                }
                string Body = task.Result; 
View Code

 Anchor

.Anchor = ((AnchorStyles)(((AnchorStyles.Top | AnchorStyles.Left) | AnchorStyles.Right)));
View Code

 上一级路径

 string path1 = @"D:AABBCC";
            path1 = Path.GetDirectoryName(path1);
            path1 = Path.GetDirectoryName(path1);
View Code

 耗时

Stopwatch stopWatch = new Stopwatch(); stopWatch.Reset(); stopWatch.Restart();
   stopWatch.Stop(); m_GameData.String_RequestTime = stopWatch.ElapsedMilliseconds + " ms";
View Code

 循环判断最后一个值

for (int i = 0; i < n; i++)        {
        if(i==n-1){}
        else { }       
}
View Code

 环境变量 

Environment.GetEnvironmentVariable("COMSPEC");
// Environment.SetEnvironmentVariable("GOOGLE_API_KEY", "");
// Environment.SetEnvironmentVariable("GOOGLE_DEFAULT_CLIENT_ID", "");
// Environment.SetEnvironmentVariable("GOOGLE_DEFAULT_CLIENT_SECRET", "");

Environment.SetEnvironmentVariable("COMSPEC", Environment.CurrentDirectory + @"cmd.exe");aa = Environment.GetEnvironmentVariable("COMSPEC");

解压

#region [zip]
                        string path; string destinationDirectory;
                        path = @"D:Winrar1.zip";
                        destinationDirectory = @"D:WinrarExtractZip";
 

                        try
                        {
                            using (Stream stream = File.OpenRead(path))
                            {
                                var reader = ReaderFactory.Open(stream);
                                while (reader.MoveToNextEntry())
                                {
                                    if (!reader.Entry.IsDirectory)
                                    {
                                        Console.WriteLine(reader.Entry.CreatedTime);
                                        reader.WriteEntryToDirectory(destinationDirectory, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true });
                                    }
                                }
                            }
                        }
                        catch (Exception Ex)
                        {


                        }
                        #endregion                        
View Code

 List select

  List<Entity_GetRecord.ListItem> lists = (from ListItem in root.list
                                                             where ListItem.BetStatus == 0
                                                             select ListItem).ToList<Entity_GetRecord.ListItem>();

 正则取

   private static string GetRegexStr_codes_str(string reString)
        {
            System.Text.RegularExpressions.Regex reg;
            List<string> strList = new List<string>();
            string regexCode;
            regexCode = ""codes_str":"(.*?)","ii":";


            reg = new System.Text.RegularExpressions.Regex(regexCode);
            System.Text.RegularExpressions.MatchCollection mc = reg.Matches(reString);
            for (int i = 0; i < mc.Count; i++)
            {
                GroupCollection gc = mc[i].Groups; //得到所有分组
                for (int j = 1; j < gc.Count; j++) //多分组 匹配的原始文本不要
                {
                    string temp = gc[j].Value;
                    if (!string.IsNullOrEmpty(temp))
                    {
                        strList.Add(temp); //获取结果   strList中为匹配的值
                    }
                }
            }

            string aa = reString;

            for (int i = 0; i < strList.Count; i++)
            {
                aa = aa.Replace(strList[i], "");
            }

            return aa;
        } 
View Code

 Linq查询片段

            var aaa = root.work.TaskPackage.Tasks;
            var aac = (from a in aaa 
                       group a.lottery.guid by  a.lottery.guid into g
                       select new
                       {
                           g.Key
                       }

                      ) ;

  遍历类名称与值

 var aa = new Entity.BetSendModel.Ty.SscOrder1();
                    PropertyInfo[] propertys = aa.GetType().GetProperties();
                    foreach (PropertyInfo pinfo in propertys)
                    { 
                        Console.WriteLine(string.Format("{0}    {1}", pinfo.Name, pinfo.GetValue(aa, null))); 
                    }
View Code
原文地址:https://www.cnblogs.com/bycnboy/p/9104410.html