关于对base.Onresize();的直观理解

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Drawing;
 6 using System.Windows.Forms;
 7 
 8 namespace Bezier
 9 {
10     class Bezier:Form
11     {
12         protected Point[] apt = new Point[4];
13 
14         static void Main(string[] args)
15         {
16             Application.Run(new Bezier());
17         }
18         public Bezier()
19         {
20             Text = "Bezier";
21             BackColor = SystemColors.Window;
22             ForeColor = SystemColors.WindowText;
23             ResizeRedraw = true;
24 
25             OnResize(EventArgs.Empty);
26         }
27         protected override void OnResize(EventArgs e)
28         {
29              //base.OnResize(e);
30 
31              int cx = ClientSize.Width;
32              int cy = ClientSize.Height;
33 
34              apt[0] = new Point(cx/4,cy/2);
35              apt[1] = new Point(cx/2,cy/4);
36              apt[2] = new Point(cx/2,3*cy/4);
37              apt[3] = new Point(3*cx/4,cy/2);
38         }
39         protected override void OnMouseDown(MouseEventArgs e)
40         {
41             Point pt;
42             if (e.Button == MouseButtons.Left)
43             {
44                 pt = apt[1];
45             }
46             else if (e.Button == MouseButtons.Right)
47             {
48                 pt = apt[2];
49             }
50             else
51                 return;
52             Cursor.Position = PointToScreen(pt);
53         }
54         protected override void OnMouseMove(MouseEventArgs e)
55         {
56             if (e.Button == MouseButtons.Left)
57             {
58                 apt[1] = new Point(e.X,e.Y);
59                 Invalidate(false);
60             }
61             else if (e.Button == MouseButtons.Right)
62             {
63                 apt[2] = new Point(e.X,e.Y);
64                 Invalidate(false);
65             }
66         }
67         protected override void OnPaint(PaintEventArgs e)
68         {
69             Graphics grfx = e.Graphics;
70             grfx.DrawBeziers(new Pen(ForeColor),apt);
71             Pen pen = new Pen(Color.FromArgb(0x80,ForeColor));
72             grfx.DrawLine(pen,apt[0],apt[1]);
73             grfx.DrawLine(pen,apt[2],apt[3]);
74         }
75     }
76 }

第29行注销掉了//base.OnResize(e);产生的效果如下:

 

 界面拖动到非常大,图形元素也没任何变化;

 

 界面拖动变小,然后再变大,可以发现图形元素没有刷新,图形产生了“缺失”。

如果启用base.OnResize(e);图形元素是随着界面变大或缩小的;如下所示

 

 这是为什么呢?

再次打开.NET Reflector看一下:

 

 可以看到,base.OnResize(e);中含有Invalidate()函数,有了这个函数,在窗体界面发生放大或缩小时,就可以调用Invalidate()进行刷新。

 

posted @ 2022-10-18 22:36  chenlight  阅读(89)  评论(0)    收藏  举报