WinForm磁性窗体吸附边缘
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #region 磁性窗体 2 3 public class MagneticManager 4 { 5 public class ChildFormInfo 6 { 7 public Form Child { get; set; } 8 public MagneticLocation Location { get; set; } 9 public MagneticState State { get; set; } 10 public bool CutstomSetLocation { get; set; } 11 } 12 13 public int Step { get; set; } 14 15 private Form m_mainForm = null; 16 private List m_childs = new List(); 17 18 public MagneticManager(Form form) 19 { 20 m_mainForm = form; 21 form.LocationChanged += MainForm_LocationChanged; 22 form.SizeChanged += MainForm_SizeChanged; 23 form.FormClosed += MainForm_FormClosed; 24 Step = 20; 25 } 26 27 public void addChild(Form childForm, MagneticLocation loc) 28 { 29 foreach (ChildFormInfo info in m_childs) 30 { 31 if (info.Child == childForm) 32 { 33 return; 34 } 35 } 36 37 ChildFormInfo childInfo = new ChildFormInfo(); 38 childInfo.Child = childForm; 39 childInfo.Location = loc; 40 childInfo.State = MagneticState.Adsorbent; 41 childInfo.CutstomSetLocation = false; 42 childForm.LocationChanged += ChildForm_LocationChanged; 43 childForm.SizeChanged += ChildForm_SizeChanged; 44 childForm.FormClosed += ChildForm_FormClosed; 45 46 m_childs.Add(childInfo); 47 adsorbentChild(childInfo); 48 } 49 50 private ChildFormInfo getInfo(Form form) 51 { 52 if (form == null) 53 { 54 return null; 55 } 56 57 foreach (ChildFormInfo info in m_childs) 58 { 59 if (info.Child == form) 60 { 61 return info; 62 } 63 } 64 65 return null; 66 } 67 68 private Point getLocation(ChildFormInfo info) 69 { 70 Point pos = Point.Empty; 71 72 switch (info.Location) 73 { 74 case MagneticLocation.Left: 75 pos = new Point(m_mainForm.Left - info.Child.Width + 14, m_mainForm.Top); 76 break; 77 case MagneticLocation.Right: 78 pos = new Point(m_mainForm.Right - 14, m_mainForm.Top); 79 break; 80 case MagneticLocation.Top: 81 pos = new Point(m_mainForm.Left, m_mainForm.Top - info.Child.Height); 82 break; 83 case MagneticLocation.Bottom: 84 pos = new Point(m_mainForm.Left, m_mainForm.Bottom); 85 break; 86 default: 87 break; 88 } 89 90 return pos; 91 } 92 93 private void setChildLocation(ChildFormInfo info, Point location) 94 { 95 if (info.Child == null) 96 { 97 return; 98 } 99 100 info.CutstomSetLocation = true; 101 info.Child.Location = location; 102 info.CutstomSetLocation = false; 103 } 104 105 private void setChildLocation(ChildFormInfo info, int x, int y) 106 { 107 setChildLocation(info, new Point(x, y)); 108 } 109 110 private void resetChildLocation(ChildFormInfo info) 111 { 112 if (info.Child == null) 113 { 114 return; 115 } 116 117 Point pos = getLocation(info); 118 setChildLocation(info, pos); 119 } 120 121 private void adsorbentChild(ChildFormInfo info) 122 { 123 info.State = MagneticState.Adsorbent; 124 resetChildLocation(info); 125 } 126 127 private void separationChild(ChildFormInfo info) 128 { 129 info.State = MagneticState.Separation; 130 } 131 132 private void MainForm_LocationChanged(object sender, EventArgs e) 133 { 134 foreach (ChildFormInfo info in m_childs) 135 { 136 if (info.State == MagneticState.Adsorbent) 137 { 138 resetChildLocation(info); 139 } 140 } 141 } 142 143 private void MainForm_SizeChanged(object sender, EventArgs e) 144 { 145 foreach (ChildFormInfo info in m_childs) 146 { 147 if (info.State == MagneticState.Adsorbent) 148 { 149 resetChildLocation(info); 150 } 151 } 152 } 153 154 private void MainForm_FormClosed(object sender, EventArgs e) 155 { 156 } 157 158 private void ChildForm_LocationChanged(object sender, EventArgs e) 159 { 160 ChildFormInfo info = getInfo(sender as Form); 161 162 if (info == null) 163 { 164 return; 165 } 166 167 if (info.CutstomSetLocation == true) 168 { 169 return; 170 } 171 172 Point location = getLocation(info); 173 174 if (info.Child.Left > location.X && info.Location == MagneticLocation.Right) 175 { 176 if (info.Child.Left - location.X > Step) 177 { 178 separationChild(info); 179 } 180 else 181 { 182 adsorbentChild(info); 183 } 184 } 185 else if (info.Child.Left < location.X && info.Location == MagneticLocation.Left) 186 { 187 if (info.Child.Left - location.X < -Step) 188 { 189 separationChild(info); 190 } 191 else 192 { 193 adsorbentChild(info); 194 } 195 } 196 if (info.Child.Top > location.Y && info.Location == MagneticLocation.Bottom) 197 { 198 if (info.Child.Top - location.Y > Step) 199 { 200 separationChild(info); 201 } 202 else 203 { 204 adsorbentChild(info); 205 } 206 } 207 else if (info.Child.Top < location.Y && info.Location == MagneticLocation.Top) 208 { 209 if (info.Child.Top - location.Y < -Step) 210 { 211 separationChild(info); 212 } 213 else 214 { 215 adsorbentChild(info); 216 } 217 } 218 } 219 220 private void ChildForm_SizeChanged(object sender, EventArgs e) 221 { 222 ChildFormInfo info = getInfo(sender as Form); 223 224 if (info != null && info.State == MagneticState.Adsorbent) 225 { 226 resetChildLocation(info); 227 } 228 } 229 230 private void ChildForm_FormClosed(object sender, EventArgs e) 231 { 232 ChildFormInfo info = getInfo(sender as Form); 233 234 if (info != null) 235 { 236 m_childs.Remove(info); 237 } 238 } 239 } 240 241 #endregionView Code
窗体标题居中代码 (如果设置无窗体边框则用不到这段)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 private void SetTitleCenter() 2 { 3 string titleMsg = "Winfrom Title"; 4 Graphics g = this.CreateGraphics(); 5 Double startingPoint = (this.Width / 2) - (g.MeasureString(titleMsg, this.Font).Width / 2); 6 Double widthOfASpace = g.MeasureString(" ", this.Font).Width; 7 String tmp = " "; 8 Double tmpWidth = 0; 9 10 while ((tmpWidth + widthOfASpace) < startingPoint) 11 { 12 tmp += " "; 13 tmpWidth += widthOfASpace; 14 } 15 this.Text = tmp + titleMsg; 16 } 17View Code
自带控件ChartToolTips 属性
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 Series.ToolTip = "Y:#VALY"; 2 //#VALX //x轴数据 3 //#VALY //y轴数据 4 //#PERCENT //百分比 5 //#AVG //平均值 6 //#INDEX //索引值 7 //#MAX //最大值 8 //#MIN //最小值 9 //#TOTAL //合计 10 //#LEGENDTEXT //显示Legend的text 11 //#SER //显示Series名称 12 13 14 15 private void Chart1_GetToolTipText(object sender, ToolTipEventArgs e) 16 { 17 // Check selected chart element and set tooltip text 18 switch (e.HitTestResult.ChartElementType) 19 { 20 case ChartElementType.Axis: 21 //e.Text = e.HitTestResult.Axis.Name; 22 break; 23 case ChartElementType.ScrollBarLargeDecrement: 24 //e.Text = "A scrollbar large decrement button"; 25 break; 26 case ChartElementType.ScrollBarLargeIncrement: 27 //e.Text = "A scrollbar large increment button"; 28 break; 29 case ChartElementType.ScrollBarSmallDecrement: 30 //e.Text = "A scrollbar small decrement button"; 31 break; 32 case ChartElementType.ScrollBarSmallIncrement: 33 //e.Text = "A scrollbar small increment button"; 34 break; 35 case ChartElementType.ScrollBarThumbTracker: 36 //e.Text = "A scrollbar tracking thumb"; 37 break; 38 case ChartElementType.ScrollBarZoomReset: 39 //e.Text = "The ZoomReset button of a scrollbar"; 40 break; 41 case ChartElementType.DataPoint: 42 int.TryParse(e.HitTestResult.Series.LegendText.Substring(2), out int ch_num); 43 if (ch_num != 110) 44 e.Text = "通道" + (cmbList[ch_num] as ComboBox).Text/*.Substring(2)*/ + " X轴 :" + (int)e.HitTestResult.Series.Points[e.HitTestResult.PointIndex].YValues[0] + "\r\n" + "与参考线差值(Δ):" + ((int)e.HitTestResult.Series.Points[e.HitTestResult.PointIndex].YValues[0] - (int)e.HitTestResult.ChartArea.CursorY.Position); 45 break; 46 case ChartElementType.Gridlines: 47 //e.Text = "网格线"; 48 break; 49 case ChartElementType.LegendArea: 50 //e.Text = "Legend Area"; 51 break; 52 case ChartElementType.LegendItem: 53 //e.Text = "Legend Item"; 54 break; 55 case ChartElementType.PlottingArea: 56 //e.Text = string.Format("X: {0}, Y: {1}", (int)e.HitTestResult.ChartArea.CursorX.Position, (int)e.HitTestResult.ChartArea.CursorY.Position); 57 break; 58 case ChartElementType.StripLines: 59 //e.Text = "Strip Lines"; 60 break; 61 case ChartElementType.TickMarks: 62 //e.Text = "Tick Marks"; 63 break; 64 case ChartElementType.Title: 65 //e.Text = "通道调试"; 66 break; 67 68 } 69 }View Code
Winform中窗体移动
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #region 窗体移动 2 private Point mouseOff;//鼠标移动位置变量 3 private bool leftFlag;//标签是否为左键 4 private void FrmMain_MouseDown(object sender, MouseEventArgs e) 5 { 6 if (e.Button == MouseButtons.Left) 7 { 8 mouseOff = new Point(-e.X, -e.Y); //得到变量的值 9 leftFlag = true; //点击左键按下时标注为true; 10 } 11 } 12 private void FrmMain_MouseMove(object sender, MouseEventArgs e) 13 { 14 if (leftFlag) 15 { 16 Point mouseSet = Control.MousePosition; 17 mouseSet.Offset(mouseOff.X, mouseOff.Y); //设置移动后的位置 18 Location = mouseSet; 19 } 20 } 21 private void FrmMain_MouseUp(object sender, MouseEventArgs e) 22 { 23 if (leftFlag) 24 { 25 leftFlag = false;//释放鼠标后标注为false; 26 } 27 } 28 #endregionView Code
判断鼠标在窗体外
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #region 判断鼠标在窗体外 2 3 4 Point p1 = this.PointToClient(Control.MousePosition);//鼠标相对窗体的位置 5 6 if (p1.X > this.ClientSize.Width || p1.X < 0 || p1.Y > this.ClientSize.Height || p1.Y < 0) 7 { 8 //判断鼠标在窗体外 9 } 10 11 12 #endregionView Code
实现Winform 里控件的拖动
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #region window中拖拽控件 2 3 4 [DllImport("user32.dll", EntryPoint = "ReleaseCapture")] 5 public static extern void ReleaseCapture(); 6 [DllImport("user32.dll", EntryPoint = "SendMessage")] 7 public static extern void SendMessage(int hwnd, int wMsg, int wParam, int lParam); 8 9 private void ActionServo1_MouseDown(object sender, MouseEventArgs e) 10 { 11 if (e.Button == MouseButtons.Left) 12 { 13 pictureBox1.BringToFront(); //将控件(控件名根据需要选择更改)置于顶层 14 ReleaseCapture(); 15 SendMessage((int)pictureBox1.Handle, 0xA1, 2, 0); 16 //Console.WriteLine(ActionServo1.Location.X+"--"+ ActionServo1.Location.Y); 17 } 18 } 19 #endregionView Code
控件大小随窗体大小等比例缩放
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public Form1() 2 { 3 InitializeComponent(); 4 x = this.Width; 5 y = this.Height; 6 setTag(this); //这里把代码添加到主窗体类中 7 } 8 9 #region 控件大小随窗体大小等比例缩放 10 private float x;//定义当前窗体的宽度 11 private float y;//定义当前窗体的高度 12 private void setTag(Control cons) 13 { 14 foreach (Control con in cons.Controls) 15 { 16 con.Tag = con.Width + ";" + con.Height + ";" + con.Left + ";" + con.Top + ";" + con.Font.Size; 17 if (con.Controls.Count > 0) 18 { 19 setTag(con); 20 } 21 } 22 } 23 private void setControls(float newx, float newy, Control cons) 24 { 25 //遍历窗体中的控件,重新设置控件的值 26 foreach (Control con in cons.Controls) 27 { 28 //获取控件的Tag属性值,并分割后存储字符串数组 29 if (con.Tag != null) 30 { 31 string[] mytag = con.Tag.ToString().Split(new char[] { ';' }); 32 //根据窗体缩放的比例确定控件的值 33 con.Width = Convert.ToInt32(System.Convert.ToSingle(mytag[0]) * newx);//宽度 34 con.Height = Convert.ToInt32(System.Convert.ToSingle(mytag[1]) * newy);//高度 35 con.Left = Convert.ToInt32(System.Convert.ToSingle(mytag[2]) * newx);//左边距 36 con.Top = Convert.ToInt32(System.Convert.ToSingle(mytag[3]) * newy);//顶边距 37 Single currentSize = System.Convert.ToSingle(mytag[4]) * newy;//字体大小 38 con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit); 39 if (con.Controls.Count > 0) 40 { 41 setControls(newx, newy, con); 42 } 43 } 44 } 45 } 46 private void Form1_Resize(object sender, EventArgs e) 47 { 48 float newx = (this.Width) / x; 49 float newy = (this.Height) / y; 50 setControls(newx, newy, this); 51 } 52 53 #endregionView Code
无边框窗体实现窗体大小可调整
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 //定义一个枚举,表示拖动方向 2 public enum MouseDirection 3 { 4 Herizontal,//水平方向拖动,只改变窗体的宽度 5 Vertical,//垂直方向拖动,只改变窗体的高度 6 Declining,//倾斜方向,同时改变窗体的宽度和高度 7 None//不做标志,即不拖动窗体改变大小 8 } 9 10 #region 无边框窗体大小可调整 11 bool isMouseDown = false; //表示鼠标当前是否处于按下状态,初始值为否 12 MouseDirection direction = MouseDirection.None;//表示拖动的方向,起始为None,表示不拖动 13 14 private void CC_MouseDown(object sender, MouseEventArgs e) 15 { 16 //鼠标按下 17 isMouseDown = true; 18 } 19 20 private void CC_MouseUp(object sender, MouseEventArgs e) 21 { 22 // 鼠标弹起, 23 24 isMouseDown = false; 25 //既然鼠标弹起了,那么就不能再改变窗体尺寸,拖拽方向置 none 26 direction = MouseDirection.None; 27 } 28 29 private void WINDOW_MouseMove(object sender, MouseEventArgs e) 30 { 31 //鼠标移动过程中,坐标时刻在改变 32 //当鼠标移动时横坐标距离窗体右边缘5像素以内且纵坐标距离下边缘也在5像素以内时,要将光标变为倾斜的箭头形状,同时拖拽方向direction置为MouseDirection.Declining 33 if (e.Location.X >= this.Width - 5 && e.Location.Y > this.Height - 5) 34 { 35 this.Cursor = Cursors.SizeNWSE; 36 direction = MouseDirection.Declining; 37 } 38 //当鼠标移动时横坐标距离窗体右边缘5像素以内时,要将光标变为倾斜的箭头形状,同时拖拽方向direction置为MouseDirection.Herizontal 39 else if (e.Location.X >= this.Width - 5) 40 { 41 this.Cursor = Cursors.SizeWE; 42 direction = MouseDirection.Herizontal; 43 } 44 //同理当鼠标移动时纵坐标距离窗体下边缘5像素以内时,要将光标变为倾斜的箭头形状,同时拖拽方向direction置为MouseDirection.Vertical 45 else if (e.Location.Y >= this.Height - 5) 46 { 47 this.Cursor = Cursors.SizeNS; 48 direction = MouseDirection.Vertical; 49 50 } 51 //否则,以外的窗体区域,鼠标星座均为单向箭头(默认) 52 else 53 { 54 this.Cursor = Cursors.Arrow; 55 direction = MouseDirection.None; 56 } 57 //设定好方向后,调用下面方法,改变窗体大小 58 ResizeWindow(); 59 } 60 61 62 private void ResizeWindow() 63 { 64 //这个判断很重要,只有在鼠标按下时才能拖拽改变窗体大小,如果不作判断,那么鼠标弹起和按下时,窗体都可以改变 65 if (!isMouseDown) 66 return; 67 //MousePosition的参考点是屏幕的左上角,表示鼠标当前相对于屏幕左上角的坐标this.left和this.top的参考点也是屏幕,属性MousePosition是该程序的重点 68 if (direction == MouseDirection.Declining) 69 { 70 //此行代码在mousemove事件中已经写过,在此再写一遍,并不多余,一定要写 71 this.Cursor = Cursors.SizeNWSE; 72 //下面是改变窗体宽和高的代码,不明白的可以仔细思考一下 73 this.Width = MousePosition.X - this.Left; 74 this.Height = MousePosition.Y - this.Top; 75 } 76 //以下同理 77 if (direction == MouseDirection.Herizontal) 78 { 79 this.Cursor = Cursors.SizeWE; 80 this.Width = MousePosition.X - this.Left; 81 } 82 else if (direction == MouseDirection.Vertical) 83 { 84 this.Cursor = Cursors.SizeNS; 85 this.Height = MousePosition.Y - this.Top; 86 } 87 //即使鼠标按下,但是不在窗口右和下边缘,那么也不能改变窗口大小 88 else 89 this.Cursor = Cursors.Arrow; 90 } 91 #endregion 92 93View Code
控件Panel边框重画
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 private void panel3_Paint(object sender, PaintEventArgs e) 2 { 3 ControlPaint.DrawBorder(e.Graphics, 4 panel3.ClientRectangle, 5 ColorTranslator.FromHtml("#F2F2F2"), 6 2, 7 ButtonBorderStyle.Solid, 8 ColorTranslator.FromHtml("#F2F2F2"), 9 2, 10 ButtonBorderStyle.Solid, 11 ColorTranslator.FromHtml("#F2F2F2"), 12 2, 13 ButtonBorderStyle.Solid, 14 ColorTranslator.FromHtml("#F2F2F2"), 15 2, 16 ButtonBorderStyle.Solid); 17 }View Code
更改datagridview表头标题颜色
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 //这个属性只能在代码中应用 属性列表中更改没效果 2 dataGridView1.EnableHeadersVisualStyles = false; 3 4 dataGridView1.EnableHeadersVisualStyles = false; 5 6 dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Red; 7View Code
更改WPF/WINFORM窗体圆角
//窗体圆角 https://learn.microsoft.com/zh-cn/windows/apps/desktop/modernize/apply-rounded-corners标签:info,控件,C#,void,private,break,窗体,con From: https://www.cnblogs.com/noaheallen/p/17325303.html