Programmatic Access to Resources

In addition to creating resources with Visual Studio or the other tools provided, you can create, manage, and use resources easily through code. An example of this application of resources would be to store some custom data for your application (for example, window sizes and positions) to be retrieved when the program was run again.

Reading and writing resources are performed with the ResourceReader and ResourceWriter classes. These objects let you deal with resources stored in streams or in files.

In the example that follows, we have prepared a simple Windows Forms application that displays a red and yellow ball on the form's surface. You can pick these balls up with the mouse and move them about. When the application is closed, it creates and writes a resource called ball_locations.resources. This resource stores the positions onscreen of the two balls so that the next time it is loaded, the application replaces the balls where you left them.

As a bonus, this application shows some simple mouse handling and the use of the ImageList to draw images on the form surface.

Listing 3.4.7. Resourcerw.cs: The Resource Read/Write Application
  1: using System;
  2: using System.Drawing;
  3: using System.Collections;
  4: using System.ComponentModel;
  5: using System.Windows.Forms;
  6: using System.Data;
  7: using System.Resources;
  8: using System.Globalization;
  9:
 10:
 11:
 12: namespace resourcerw
 13: {
 14:   /// <summary>
 15:   /// Summary description for Form1.
 16:   /// </summary>
 17:   public class Form1 : System.Windows.Forms.Form
 18:   {
 19:     private System.Windows.Forms.ImageList imageList1;
 20:     private System.ComponentModel.IContainer components;
 21:     private System.Drawing.Point[] BallLocations;
 22:
 23:     private bool _mousedown;
 24:     private int _grabbed;
 25:
 26:     public Form1()
 27:     {
 28:       //
 29:       // Required for Windows Form Designer support
 30:       //
 31:       InitializeComponent();
 32:
 33:       //
 34:       // TODO: Add any constructor code after InitializeComponent call
 35:       //
 36:
 37:       this.BallLocations=new System.Drawing.Point[2];
 38:
 39:     }
 40:
 41:     /// <summary>
 42:     /// Clean up any resources being used.
 43:     /// </summary>
 44:     protected override void Dispose( bool disposing )
 45:     {
 46:       if( disposing )
 47:       {
 48:         if (components != null)
 49:         {
 50:           components.Dispose();
 51:         }
 52:       }
 53:       base.Dispose( disposing );
 54:     }
 55:
 56:     #region Windows Form Designer generated code
 57:     /// <summary>
 58:     /// Required method for Designer support - do not modify
 59:     /// the contents of this method with the code editor.
 60:     /// </summary>
 61:     private void InitializeComponent()
 62:     {
 63:       this.components = new System.ComponentModel.Container();
 64:       System.Resources.ResourceManager resources =
 65:          new System.Resources.ResourceManager(typeof(Form1));
 66:       this.imageList1 =
 67:          new System.Windows.Forms.ImageList(this.components);
 68:       //
 69:       // imageList1
 70:       //
 71:       this.imageList1.ColorDepth =
 72:          System.Windows.Forms.ColorDepth.Depth8Bit;
 73:       this.imageList1.ImageSize = new System.Drawing.Size(64, 64);
 74:       this.imageList1.ImageStream =
 75:          ((System.Windows.Forms.ImageListStreamer)
 76:           (resources.GetObject("imageList1.ImageStream")));
 77:       this.imageList1.TransparentColor = System.Drawing.Color.Magenta;
 78:       //
 79:       // Form1
 80:       //
 81:       this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
 82:       this.BackColor = System.Drawing.Color.Green;
 83:       this.ClientSize = new System.Drawing.Size(376, 301);
 84:       this.Name = "Form1";
 85:       this.Text = "Resource read-write";
 86:       this.MouseDown +=
 87:         new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown);
 88:       this.Closing +=
 89:         new System.ComponentModel.CancelEventHandler(this.Form1_Closing);
 90:       this.Load +=
 91:         new System.EventHandler(this.Form1_Load);
 92:       this.MouseUp +=
 93:         new System.Windows.Forms.MouseEventHandler(this.Form1_MouseUp);
 94:       this.Paint +=
 95:         new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);
 96:       this.MouseMove +=
 97:         new System.Windows.Forms.MouseEventHandler(this.Form1_MouseMove);
 98:
 99:     }
100:     #endregion
101:
102:     /// <summary>
103:     /// The main entry point for the application.
104:     /// </summary>
105:     [STAThread]

106:     static void Main()
107:     {
108:       Application.Run(new Form1());
109:     }
110:
111:
112:     private void Form1_MouseMove(object sender,
113:          System.Windows.Forms.MouseEventArgs e)
114:     {
115:       if(_mousedown && (_grabbed!=-1))
116:       {
117:         if(e.X>31 && e.Y>31 && e.X<(this.Size.Width-32) &&
118:           e.Y<(this.Size.Height-32))
119:         {
120:           BallLocations[_grabbed].X=e.X;
121:           BallLocations[_grabbed].Y=e.Y;
122:
123:           this.Invalidate();
124:         }
125:       }
126:     }
127:
128:     private void Form1_MouseUp(object sender,
129:           System.Windows.Forms.MouseEventArgs e)
130:     {
131:       _mousedown=false;
132:     }
133:
134:     private void Form1_MouseDown(object sender,
135:              System.Windows.Forms.MouseEventArgs e)
136:     {
137:       _mousedown=true;
138:       int index=0;
139:       _grabbed=-1;
140:       foreach(Point p in this.BallLocations)
141:       {
142:         if(Math.Abs(e.X-p.X)<32 && Math.Abs(e.Y-p.Y)<32)
143:           _grabbed=index;
144:         index++;
145:       }
146:     }
147:
148:     private void Form1_Paint(object sender,
149:              System.Windows.Forms.PaintEventArgs e)
150:     {
151:       int index=0;
152:       foreach(Point p in this.BallLocations)
153:       {
154:         this.imageList1.Draw(e.Graphics,p.X-32,p.Y-32,64,64,index++);
155:       }
156:     }
157:
158:     private void Form1_Load(object sender, System.EventArgs e)
159:     {
160:
161:       ResourceSet rs;
162:
163:       try
164:       {
165:         rs = new ResourceSet("ball_locations.resources");
166:         BallLocations[0] = (Point)rs.GetObject("RedBall",false);
167:         BallLocations[1] = (Point)rs.GetObject("YellowBall",false);
168:         rs.Close();
169:       }
170:       catch(System.Exception)
171:       {
172:         // Any old exception will do, probably file not yet created...
173:         BallLocations[0]=new Point(100,100);
174:         BallLocations[1]=new Point(200,200);
175:       }
176:
177:     }
178:
179:     private void Form1_Closing(object sender,
180:              System.ComponentModel.CancelEventArgs e)
181:     {
182:       // Write the ball positions to the custom resource
183:       // note you can just write objects.
184:       ResourceWriter rw = new ResourceWriter("ball_locations.resources");
185:       rw.AddResource("RedBall",this.BallLocations[0]);
186:       rw.AddResource("YellowBall",this.BallLocations[1]);
187:       rw.Generate();
188:       rw.Close();
189:     }
190:
191:
192:   }
193: }

Lines 61–99 show the InitializeComponent method required by Visual Studio. Lines 63–65 open the image resources used by the ImageList object, and lines 66–77 initialize the ImageList by loading in the image stream and setting the parameters for size and transparent color. Lines 86–97 add the mouse and paint other handlers.

Now for the event handlers themselves. The two important ones are the form loading and form closing events. Lines 158–175 are the form load event handler. This attempts to open a resource and get the ball positions from it. If this fails for any reason, an exception handler simply assumes that the file doesn't exist and initializes both balls to their default positions. Lines 179–188 are invoked when the form is ready to close. Here, the code creates a resource file and stores all the ball positions in it. The next time the program is run, this file will exist and the load event handler will successfully find the stored positions.

The MouseUp handler (lines 128–132) simply resets a semaphore that signifies no dragging is taking place. The MouseDown handler (lines 134–146) decides which of the two balls, if any, the mouse is in, and flags the correct one to grab.

The MouseMove handler checks to see if a ball is grabbed and if the mouse is inside the client area, so that you cannot drag a ball off the screen. All being correct, it updates the position of the currently active ball. This method is found on lines 112–126.

Lastly, on lines 148–156 the Paint handler paints the balls on the surface of the form.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.171.130