1using System;
2using System.Windows.Form;
3
4namespace Utilities
5{
6 /// <summary>
7 /// A utility class that show a static layout of a <see cref="Form" />
8 /// when in the background the content itself is refreshed.
9 /// </summary>
10 public class FormFreezer : IDisposable
11 {
12 // The form being frozen
13 Form form;
14
15 // the auxiliary PictureBox that will cover the form
16 PictureBox pictureBox;
17
18 // the number of times the Freeze method has been called
19 int FreezeCount = 0;
20
21 // create an instance associated with a given form
22 // and freeze the form in base of flag freezeIt
23 public FormFreezer(Form form, bool freezeIt)
24 {
25
26 this.form = form;
27 if (freezeIt)
28 this.Freeze();
29 }
30
31
32 // freeze the form
33 public void Freeze()
34 {
35 // Remember we have frozen the form once more
36 // Do nothing if it was already frozen
37 if (++FreezeCount > 1)
38 return;
39
40 // Create a PictureBox that resizes with its contents
41 pictureBox = new PictureBox();
42 pictureBox.SizeMode = PictureBoxSizeMode.AutoSize;
43
44 // create a bitmap as large as the form's client area and with same color depth
45 Graphics frmGraphics = form.CreateGraphics();
46 Rectangle rect = form.ClientRectangle;
47 pictureBox.Image = new Bitmap(rect.Width, rect.Height, frmGraphics);
48 frmGraphics.Dispose();
49
50 // copy the screen contents, from the form's client area to the hidden bitmap
51 Graphics picGraphics = Graphics.FromImage(pictureBox.Image);
52 picGraphics.CopyFromScreen(form.PointToScreen(new Point(rect.Left, rect.Top)), new Point(0, 0), new Size(rect.Width, rect.Height));
53 picGraphics.Dispose();
54
55 // Display the bitmap in the picture box, and show the picture box in front of all other controls
56 form.Controls.Add(pictureBox);
57 pictureBox.BringToFront();
58 }
59
60 // unfreeze the form
61 // Note: calls to Freeze and Unfreeze must be balanced, unless force=true
62 public void Unfreeze(bool force)
63 {
64 // exit if nothing to unfreeze
65 if (FreezeCount == 0)
66 return;
67
68 // remember we've unfrozen the form, but exit if it is still frozen
69 FreezeCount -= 1;
70
71 // force the unfreeze if so required
72 if (force)
73 FreezeCount = 0;
74
75 if (FreezeCount > 0)
76 return;
77
78 // remove the picture box control and clean up
79 pictureBox.Controls.Remove(pictureBox);
80 pictureBox.Dispose();
81 pictureBox = null;
82 }
83
84 // return true if the form is currently frozen
85 public bool IsFrozen
86 {
87 get { return (FreezeCount > 0); }
88 }
89
90 void IDisposable.Dispose()
91 {
92 this.Unfreeze(true);
93 }
94 }
95}