Скачиваний:
64
Добавлен:
15.03.2015
Размер:
4.31 Mб
Скачать

Windows Forms Example Application (Scribble .NET)

315

CHAPTER 3.4

LISTING 3.4.6 Continued

20:this.imageList1.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit;

21:this.imageList1.ImageSize = new System.Drawing.Size(16, 16);

22:this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)

23:(resources.GetObject(“imageList1.ImageStream”)));

24:this.imageList1.TransparentColor = System.Drawing.Color.Magenta;

25://

26:// listView1

27://

28:listViewItem1.UseItemStyleForSubItems = false;

29:listViewItem2.UseItemStyleForSubItems = false;

30:listViewItem3.UseItemStyleForSubItems = false;

31:listViewItem4.UseItemStyleForSubItems = false;

32:this.listView1.Items.AddRange(new System.Windows.Forms.ListViewItem[] {

33:listViewItem1,

34:listViewItem2,

35:listViewItem3,

36:listViewItem4});

37:this.listView1.Location = new System.Drawing.Point(8, 8);

38:this.listView1.Name = “listView1”;

39:this.listView1.Size = new System.Drawing.Size(272, 200);

40:this.listView1.SmallImageList = this.imageList1;

41:this.listView1.TabIndex = 0;

42:this.listView1.View = System.Windows.Forms.View.SmallIcon;

43://

44:// Form1

45://

46:this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);

47:this.ClientSize = new System.Drawing.Size(292, 273);

48:this.Controls.AddRange(new System.Windows.Forms.Control[]

49:{ this.listView1});

50:this.Name = “Form1”;

51:this.Text = “Form1”;

52:this.ResumeLayout(false);

53:}

Now, lines 6–13 create the ListViewItem objects and set the text and image offset within the ImageList to use. Lines 32–36 add the items to the ListView.

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.

3.4

INDOWSWEA FXAMPLEPPLICATION ORMS

Windows Forms

316

PART III

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;

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;

26:public Form1()

27:{

28://

29:// Required for Windows Form Designer support

30://

31:InitializeComponent();

32:

Windows Forms Example Application (Scribble .NET)

CHAPTER 3.4

LISTING 3.4.7 Continued

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;

317

3.4

INDOWSWEA FXAMPLEPPLICATION ORMS

Windows Forms

318

PART III

LISTING 3.4.7 Continued

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);

99:}

100:#endregion

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:

Windows Forms Example Application (Scribble .NET)

CHAPTER 3.4

LISTING 3.4.7 Continued

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);

319

3.4

INDOWSWEA FXAMPLEPPLICATION ORMS

Windows Forms

320

PART III

LISTING 3.4.7 Continued

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.