using Microsoft.CSharp; using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; namespace MetroGauges { public class Utily { ///   /// 获取中心点坐标  ///   ///   ///   public static Point GetCenterPoint(Point[] p) { Point ptCenter = new Point(0, 0); int i, j; double ai, atmp = 0, xtmp = 0, ytmp = 0; if (p == null) throw new ArgumentNullException("获取多边形中心点坐标时传入的参数为空。"); if (p.Length == 1) return p[0]; if ((p.Length == 2) || (p.Length == 3 && p[0] == p[2])) return new Point((p[1].X + p[0].X) / 2, (p[1].Y + p[0].Y) / 2); int n = p.Length; for (i = n - 1, j = 0; j < n; i = j, j++) { ai = p[i].X * p[j].Y - p[j].X * p[i].Y; atmp += ai; xtmp += (p[j].X + p[i].X) * ai; ytmp += (p[j].Y + p[i].Y) * ai; } if (atmp != 0) { ptCenter.X = Convert.ToInt32(xtmp / (3 * atmp)); ptCenter.Y = Convert.ToInt32(ytmp / (3 * atmp)); } return ptCenter; } public static bool isInputNumber(KeyEventArgs e) { if (e.Key == Key.OemMinus) { return true; } if ((e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Delete || e.Key == Key.Back || e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.OemPeriod) { //按下了Alt、ctrl、shift等修饰键 if (e.KeyboardDevice.Modifiers != ModifierKeys.None) { e.Handled = true; } else { return true; } } else//按下了字符等其它功能键 { e.Handled = true; } return false; } /// /// 向上查找控件 /// /// /// /// public static DependencyObject VisualUpwardSearch(DependencyObject source) { while (source != null && source.GetType() != typeof(T)) source = VisualTreeHelper.GetParent(source); return source; } /// /// 向下查找控件 /// /// /// /// public static T SearchVisualTree(DependencyObject tarElem) where T : DependencyObject { var count = VisualTreeHelper.GetChildrenCount(tarElem); if (count == 0) return null; for (int i = 0; i < count; ++i) { var child = VisualTreeHelper.GetChild(tarElem, i); if (child != null && child is T) { return (T)child; } else { var res = SearchVisualTree(child); if (res != null) { return res; } } } return null; } public static TreeViewItem GetNearestContainer(UIElement element) { TreeViewItem container = element as TreeViewItem; while ((container == null) && (element != null)) { element = VisualTreeHelper.GetParent(element) as UIElement; container = element as TreeViewItem; } return container; } /// /// 根据邦定类型查找 TreeViewItem /// /// /// /// public static TreeViewItem FindTreeViewItem(ItemsControl item, object data) { TreeViewItem findItem = null; bool itemIsExpand = false; if (item is TreeViewItem) { TreeViewItem tviCurrent = item as TreeViewItem; itemIsExpand = tviCurrent.IsExpanded; if (!tviCurrent.IsExpanded) { //如果这个TreeViewItem未展开过,则不能通过ItemContainerGenerator来获得TreeViewItem tviCurrent.SetValue(TreeViewItem.IsExpandedProperty, true); //必须使用UpdaeLayour才能获取到TreeViewItem tviCurrent.UpdateLayout(); } } for (int i = 0; i < item.Items.Count; i++) { TreeViewItem tvItem = (TreeViewItem)item.ItemContainerGenerator.ContainerFromIndex(i); if (tvItem == null) continue; object itemData = item.Items[i]; if (itemData == data) { findItem = tvItem; break; } else if (tvItem.Items.Count > 0) { findItem = FindTreeViewItem(tvItem, data); if (findItem != null) break; } } if (findItem == null) { TreeViewItem tviCurrent = item as TreeViewItem; if (tviCurrent != null) { tviCurrent.SetValue(TreeViewItem.IsExpandedProperty, itemIsExpand); tviCurrent.UpdateLayout(); } } return findItem; } /// /// 使用反射 动态创建类,将DataTable的列名动态添加为该类的属性,并给属性赋值 /// 该方法由于要动态创建类,性能比较低(注意只是将DataTable的第一行转换为动态实体类) /// /// /// public static Object CreatNewClassBydt(string classname, ObservableCollection fieldInfos ) { if (fieldInfos == null || fieldInfos.Count < 1) { return new object(); } //创建编译器实例。 CSharpCodeProvider provider = new CSharpCodeProvider(); //设置编译参数。 CompilerParameters paras = new CompilerParameters(); paras.GenerateExecutable = false; paras.GenerateInMemory = true; //paras.OutputAssembly = "c:\\1.dll"; paras.ReferencedAssemblies.Add("System.dll"); paras.ReferencedAssemblies.Add("System.Data.dll"); //创建动态代码。 StringBuilder classSource = new StringBuilder(); classSource.Append("public class "+ classname + " \n"); classSource.Append("{\n"); //创建属性。 foreach (var cl in fieldInfos) { classSource.Append(propertyString(cl.Display)); } classSource.Append("}"); System.Diagnostics.Debug.WriteLine(classSource.ToString()); //编译代码。 CompilerResults result = provider.CompileAssemblyFromSource(paras, classSource.ToString()); if (result.Errors.Count > 0) { for (int i = 0; i < result.Errors.Count; i++) Console.WriteLine(result.Errors[i]); Console.WriteLine("error"); return null; } //获取编译后的程序集。 Assembly assembly = result.CompiledAssembly; object obclass = assembly.CreateInstance(classname); foreach (var cl in fieldInfos) { //ReflectionSetProperty(obclass, cl.ColumnName, dt.Rows[0][cl.ColumnName].ToString()); PropertyInfo _Property = obclass.GetType().GetProperty(cl.Display); if (_Property != null) { _Property.SetValue(obclass, cl.Fieldvalue, null); } } return obclass; } private static string propertyString(string propertyName) { StringBuilder sbProperty = new StringBuilder(); sbProperty.Append(" private string _" + propertyName + " =string.Empty;\n"); sbProperty.Append(" public string " + "" + propertyName + "\n"); sbProperty.Append(" {\n"); sbProperty.Append(" get{ return _" + propertyName + ";} \n"); sbProperty.Append(" set{ _" + propertyName + " = value; }\n"); sbProperty.Append(" }"); return sbProperty.ToString(); } //将Image转换成流数据,并保存为byte[] public static byte[] PhotoImageInsert(System.Drawing.Image imgPhoto) { MemoryStream mstream = new MemoryStream(); imgPhoto.Save(mstream, System.Drawing.Imaging.ImageFormat.Bmp); byte[] byData = new Byte[mstream.Length]; mstream.Position = 0; mstream.Read(byData, 0, byData.Length); mstream.Close(); return byData; } public static BitmapImage BitmapToBitmapImage(byte[] img) { BitmapImage bitmapImage = new BitmapImage(); using (System.IO.MemoryStream ms = new System.IO.MemoryStream(img)) { bitmapImage.BeginInit(); bitmapImage.StreamSource = ms; bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.EndInit(); bitmapImage.Freeze(); } return bitmapImage; } public static BitmapImage BitmapToBitmapImage(System.Drawing.Bitmap bitmap) { BitmapImage bitmapImage = new BitmapImage(); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { bitmap.Save(ms, bitmap.RawFormat); bitmapImage.BeginInit(); bitmapImage.StreamSource = ms; bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.EndInit(); bitmapImage.Freeze(); } return bitmapImage; } } }