-
Notifications
You must be signed in to change notification settings - Fork 0
/
Form1.cs
1203 lines (1091 loc) · 49.5 KB
/
Form1.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Media;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ShapesGraphics
{
[Flags]
public enum ShapeType { LINE = 1 << 0,
CIRCLE = 1 << 1,
RECTANGLE = 1 << 2,
FREE = 1 << 3 };
public partial class Form1 : Form
{
const string APP_NAME = "Shapes Graphics ";
const string ALL_SHAPES = "All shapes";
const string LINES_ONLY = "Lines only";
const string CIRCLES_ONLY = "Circles only";
const string RECTANGLES_ONLY = "Rectangles only";
const string FREESHAPE_ONLY = "Free draw only";
const int FREESHAPE_BYPASS = 99999;
// The bypass value is used when the mouse-up event of the free-drawing is OUTSIDE of the panel
// But we still want to add the shape in the mouse click event....
Pen pen;
Brush brush;
Image image;
Color currentColor;
HashSet<Button> shapesButtonsSet;
ShapeContainer sc; // the shapes container
ShapeType chosenShape; // the current chosen shape to draw
int clickEvent; // to know if first click or second click
Point startPoint; // x,y of first click
Point endPoint; // x,y of second click
Shape shapeClicked; // the shape under the right click
Shape clonedShape; // for copy/paste !
Point rightClickPoint; // right click location
bool dirty; // for file save...
string saveFileName; // the chosen file name to save to
string imageFileName; // for filling shape with image
bool freeDraw; // for mouse free drawing
int prevX, prevY; // used for free drawing
List<Point> freeDrawShape; // to store all the x y from free drawing before adding to container
public Form1()
{
// 1. Init Form
InitializeComponent();
// 2. Init Form Data
sc = new ShapeContainer(50);
chosenShape = ShapeType.LINE;
pictureBoxCurrentColor.BackColor = currentColor = Color.DarkCyan;
pen = new Pen(currentColor,int.Parse(comboBoxPenWidth.Text));
brush = new SolidBrush(currentColor);
image = null;
clickEvent = 0;
dirty = false;
// 3. Init Tool Bars
this.statusBarToolStripMenuItem.Image = ShapesGraphics.Properties.Resources.GreenCheck;
this.pasteToolStripMenuItem.Enabled = false;
// 4. Init Shapes Buttons
shapesButtonsSet = new HashSet<Button>();
shapesButtonsSet.Add(buttonLine);
shapesButtonsSet.Add(buttonCircle);
shapesButtonsSet.Add(buttonRectangle);
shapesButtonsSet.Add(buttonFree);
// 5. Create bitmaps for Buttons pictures...
Bitmap bmpLine = new Bitmap(50, 50);
Graphics gg = Graphics.FromImage(bmpLine);
gg.Clear(Color.Transparent);
gg.DrawLine(new Pen(Color.DarkBlue, 4), new System.Drawing.Point(14, 36), new System.Drawing.Point(36, 14));
buttonLine.Image = bmpLine;
Bitmap bmpCircle = new Bitmap(50, 50);
gg = Graphics.FromImage(bmpCircle);
gg.Clear(Color.Transparent);
gg.DrawEllipse(new Pen(Color.DarkBlue, 4), 12, 12, 26, 26);
buttonCircle.Image = bmpCircle;
Bitmap bmpRectangle = new Bitmap(50, 50);
gg = Graphics.FromImage(bmpRectangle);
gg.Clear(Color.Transparent);
gg.DrawRectangle(new Pen(Color.DarkBlue, 4), 12, 13, 25, 25);
buttonRectangle.Image = bmpRectangle;
// 6. Subscribe to the shapes container area events !
SubscribeToAreaEvents();
}
private void SubscribeToAreaEvents()
{
// 6.1 Original way
//sc.tooSmallAreaEvent += new Action<bool>(areaTooSmallHandler);
//sc.tooLargeAreaEvent += new Action<bool>(areaTooLargeHandler);
// 6.2 Using anonymous method
sc.tooSmallAreaEvent += delegate(bool value) { textBoxDecrease.Enabled = !value; };
// 6.3 Using Lanbda
sc.tooLargeAreaEvent += (value) => { textBoxIncrease.Enabled = !value; };
}
//private void areaTooSmallHandler(bool value)
//{
// // if (value == true) it means that the area of the smalles shape is less than the minimum
// textBoxDecrease.Enabled = ! value; //
//}
//private void areaTooLargeHandler(bool value)
//{
// // if (value == true) it means that the area of the largest shape is greater than the maximum
// textBoxIncrease.Enabled = ! value;
//}
private void buttonChooseColor_Click(object sender, EventArgs e)
{
// Open color dialog
if (colorDialog1.ShowDialog() == DialogResult.OK)
{
if (colorDialog1.Color == Color.White)
{
MessageBox.Show("White color will not be seen, choose another color...", "Note");
colorDialog1.Color = currentColor;
}
else
{
pictureBoxCurrentColor.BackColor = currentColor = colorDialog1.Color;
pictureBoxColor1.BackColor = currentColor;
}
}
clickEvent = 0;
}
private void pictureBoxCurrentColor_Click(object sender, EventArgs e)
{
buttonChooseColor_Click(sender, e);
}
private void comboBoxViewAll_SelectedValueChanged(object sender, EventArgs e)
{
// Go over List and set show/hide param
ShapeType type = ShapeType.LINE | ShapeType.CIRCLE | ShapeType.RECTANGLE | ShapeType.FREE; // The 'All' option
switch (comboBoxViewAll.Text)
{
case LINES_ONLY:
{
type = ShapeType.LINE;
if (chosenShape != ShapeType.LINE) buttonLine_Click(sender, e);
break;
}
case CIRCLES_ONLY:
{
type = ShapeType.CIRCLE;
if (chosenShape != ShapeType.CIRCLE) buttonCircle_Click(sender, e);
break;
}
case RECTANGLES_ONLY:
{
type = ShapeType.RECTANGLE;
if (chosenShape != ShapeType.RECTANGLE) buttonRectangle_Click(sender, e);
break;
}
case FREESHAPE_ONLY:
{
type = ShapeType.FREE;
if (chosenShape != ShapeType.FREE) buttonFree_Click(sender, e);
break;
}
}
sc.SetShowType(type);
labelViewStyle.Text = (comboBoxViewAll.Text.Equals(ALL_SHAPES)) ? "" : comboBoxViewAll.Text + " view";
panel1.Refresh();
}
private void buttonRemoveAll_Click(object sender, EventArgs e)
{
// Clear all
sc.RemoveAll();
// Init static input order count
Shape.InputOrder = 0;
PostChangeActions();
clickEvent = 0;
}
private void buttonRemoveLast_Click(object sender, EventArgs e)
{
// Remove last only if in 'all shapes view'
if (comboBoxViewAll.Text == ALL_SHAPES)
{
// Clear only last shape entered ( the one with the highest input order ...)
sc.RemoveLastInput();
PostChangeActions();
clickEvent = 0;
}
else
MessageBox.Show("'All Shapes View' must be enabled before removing last shape !","Note:");
}
private void buttonLine_Click(object sender, EventArgs e)
{
chosenShape = ShapeType.LINE;
SetShapesButtonsColor(buttonLine);
checkBoxFillShape.Checked = false;
checkBoxFillShape.Enabled = false;
SetLineStyleButtons(true);
// set default order viewing options before continue drawing..
SetDevaultOrderView();
string viewType = comboBoxViewAll.Text;
if (viewType.Equals(CIRCLES_ONLY) || viewType.Equals(RECTANGLES_ONLY) || viewType.Equals(FREESHAPE_ONLY))
comboBoxViewAll.Text = ALL_SHAPES;
clickEvent = 0;
}
private void buttonCircle_Click(object sender, EventArgs e)
{
chosenShape = ShapeType.CIRCLE;
SetShapesButtonsColor(buttonCircle);
SetLineStyleButtons(true);
checkBoxFillShape.Enabled = true;
radioButtonImage.Enabled = false;
labelRed.Visible = false;
if (radioButtonImage.Checked) radioButtonSolidFill.Checked = true;
// set default order viewing options before continue drawing..
SetDevaultOrderView();
string viewType = comboBoxViewAll.Text;
if (viewType.Equals(LINES_ONLY) || viewType.Equals(RECTANGLES_ONLY) || viewType.Equals(FREESHAPE_ONLY))
comboBoxViewAll.Text = ALL_SHAPES;
clickEvent = 0;
}
private void buttonRectangle_Click(object sender, EventArgs e)
{
chosenShape = ShapeType.RECTANGLE;
SetShapesButtonsColor(buttonRectangle);
SetLineStyleButtons(true);
checkBoxFillShape.Enabled = true;
radioButtonImage.Enabled = true;
// set default order viewing options before continue drawing..
SetDevaultOrderView();
string viewType = comboBoxViewAll.Text;
if (viewType.Equals(LINES_ONLY) || viewType.Equals(CIRCLES_ONLY) || viewType.Equals(FREESHAPE_ONLY))
comboBoxViewAll.Text = ALL_SHAPES;
clickEvent = 0;
}
private void buttonFree_Click(object sender, EventArgs e)
{
chosenShape = ShapeType.FREE;
SetShapesButtonsColor(buttonFree);
checkBoxFillShape.Checked = false;
checkBoxFillShape.Enabled = false;
SetLineStyleButtons(false);
// set default order viewing options before continue drawing..
SetDevaultOrderView();
string viewType = comboBoxViewAll.Text;
if (viewType.Equals(LINES_ONLY) || viewType.Equals(CIRCLES_ONLY) || viewType.Equals(RECTANGLES_ONLY))
comboBoxViewAll.Text = ALL_SHAPES;
clickEvent = 0;
}
private void SetDevaultOrderView()
{
if (!radioButtonViewByOrder.Checked)
radioButtonViewByOrder.Checked = true;
}
private void SetLineStyleButtons(bool value)
{
radioButtonDashDot.Enabled = value;
radioButtonDashDotDot.Enabled = value;
radioButtonDottedLine.Enabled = value;
}
private void SetShapesButtonsColor(Button btn)
{
foreach (Button b in shapesButtonsSet)
if (b.Equals(btn))
b.BackColor = Color.SandyBrown;
else
b.BackColor = SystemColors.Control;
}
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern IntPtr WindowFromPoint(System.Drawing.Point p);
private void panel1_MouseClick(object sender, MouseEventArgs e)
{
bool shapeWasAdded = false;
// Convert screen points to control points
System.Drawing.Point p1 = panel1.PointToClient(Control.MousePosition);
// *** Right Click ***
if (e.Button == MouseButtons.Right)
{
// If Shape detected under -OR- there is a cloned shape for 'Paste' action, then open context menu
rightClickPoint = new Point(p1.X, p1.Y);
shapeClicked = sc.GetShapeAtPosition(rightClickPoint);
if ((shapeClicked != null) || (clonedShape != null))
{
// 1. Set views
if (shapeClicked != null)
{
// 1.1 Show details on status bar
statusStrip1.Items[3].Text = shapeClicked.ToString();
statusStrip1.Items[3].ForeColor = Color.Firebrick;
SetStatusBarView(false, true);
// 1.2 Set view options in context menu
copyToolStripMenuItem.Enabled = cutToolStripMenuItem.Enabled = removeToolStripMenuItem.Enabled = true;
if (sc.Size() > 1)
sendToBackToolStripMenuItem.Enabled = bringToFrontToolStripMenuItem.Enabled = true;
else
sendToBackToolStripMenuItem.Enabled = bringToFrontToolStripMenuItem.Enabled = false;
}
else
{
copyToolStripMenuItem.Enabled = cutToolStripMenuItem.Enabled = removeToolStripMenuItem.Enabled =
sendToBackToolStripMenuItem.Enabled = bringToFrontToolStripMenuItem.Enabled = false;
}
// 2. Open context menu
contextMenuStrip1.Show(panel1, p1);
clickEvent = 0;
}
}
// *** Left Click ***
else
{
// Find the control where the mouse click occured
// var hwnd = WindowFromPoint(Control.MousePosition);
var hwnd = WindowFromPoint(Cursor.Position);
var c = Control.FromHandle(hwnd);
if ((c == panel1) || (e.Clicks == FREESHAPE_BYPASS))
{
if (clickEvent == 0)
{
// 1. This is the first click
clickEvent = 1;
// 2. Only record the x,y position of mouse
startPoint = new Point(p1.X, p1.Y);
}
else if (clickEvent == 1)
{
// 1. This is the second click
clickEvent = 0;
// Go back to this viewing option before continue drawing..
if (!radioButtonViewByOrder.Checked)
radioButtonViewByOrder.Checked = true;
// 2. Now record the x,y position of mouse
endPoint = new Point(p1.X, p1.Y);
string showType = comboBoxViewAll.Text;
// 3. Now add the chosen shape to shape container
switch (chosenShape)
{
case ShapeType.LINE:
{
SetPenBrushImage(1, 1);
Line line = new Line(startPoint, currentColor, endPoint, pen, brush);
line.Show = (showType == ALL_SHAPES) || (showType == LINES_ONLY) ? true : false;
sc.Add(line);
shapeWasAdded = true;
break;
}
case ShapeType.CIRCLE:
{
// Swap points if drawing from right to left..
Point tempE = endPoint;
Point tempS = startPoint;
if ((endPoint.X < startPoint.X) && (endPoint.Y >= startPoint.Y))
{
startPoint.X = tempE.X;
endPoint.X = tempS.X;
}
if ((endPoint.X < startPoint.X) && (endPoint.Y < startPoint.Y))
{
startPoint = tempE;
endPoint = tempS;
}
if ((endPoint.X > startPoint.X) && (endPoint.Y < startPoint.Y))
{
startPoint.Y = tempE.Y;
endPoint.Y = tempS.Y;
}
float radius = endPoint.Distance(startPoint);
if (radius != 0) // if radius is != 0
{
SetPenBrushImage((int)radius, (int)radius);
Circle circle = new Circle(startPoint, currentColor, checkBoxFillShape.Checked, pen, brush, radius, image);
circle.Show = (showType == ALL_SHAPES) || (showType == CIRCLES_ONLY) ? true : false;
sc.Add(circle);
shapeWasAdded = true;
}
else
// Consider click as not performed...since circle with 0 radius is NOT added.
clickEvent = 1;
break;
}
case ShapeType.RECTANGLE:
{
// Swap points if drawing from right to left..
if (endPoint.X < startPoint.X)
{
int temp = endPoint.X;
endPoint.X = startPoint.X;
startPoint.X = temp;
}
if (endPoint.Y < startPoint.Y)
{
int temp = endPoint.Y;
endPoint.Y = startPoint.Y;
startPoint.Y = temp;
}
int width = endPoint.X - startPoint.X;
int height = endPoint.Y - startPoint.Y;
if ((width != 0) && (height != 0))
{
try
{
// Exception will be thrown if image file was not selected for image fill type
SetPenBrushImage(width, height);
Rectangle rect = new Rectangle(startPoint, currentColor, checkBoxFillShape.Checked, pen, brush,
width, height, image);
rect.Show = (showType == ALL_SHAPES) || (showType == RECTANGLES_ONLY) ? true : false;
sc.Add(rect);
shapeWasAdded = true;
}
catch
{
// Nothing to do, shape will just not be added, user will just need to select an image file
}
}
else
// Consider click as not performed...since recangle with 0 width/height is NOT added.
clickEvent = 1;
break;
}
case ShapeType.FREE:
{
if (freeDrawShape.Count > 1)
{
SetPenBrushImage(1, 1);
FreeDraw freeShape = new FreeDraw(new Point(freeDrawShape[0].X,freeDrawShape[0].Y),
currentColor, freeDrawShape, pen, brush);
freeShape.Show = (showType == ALL_SHAPES) || (showType == FREESHAPE_ONLY) ? true : false;
sc.Add(freeShape);
shapeWasAdded = true;
}
else
// Consider click as not performed...since free shape with 1 cell length is NOT added.
clickEvent = 1;
break;
}
default:
{
MessageBox.Show("Invalid Shape Passed");
break;
}
}
// 4. Post addition actions
if (shapeWasAdded)
{
PostChangeActions();
}
}
}
}
}
private void PostChangeActions()
{
// 5. Sort shapes according to the view option chosen
if (radioButtonViewSmallestOnTop.Checked)
sc.Sort(new SortLargeToSmall()); // smallest on top
else if (radioButtonViewLargestOnTop.Checked)
sc.Sort(); // largest on top
// 6. Refresh panel to redraw shapes
panel1.Refresh();
dirty = true;
if (this.Text[this.Text.Length - 1] != '*')
this.Text += '*';
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
// Draw Grid
if (this.gridLinesToolStripMenuItem.Image != null)
DrawGrid(Color.LightGray);
else
DrawGrid(panel1.BackColor);
// Draw Shapes
Graphics g = panel1.CreateGraphics();
sc.DrawAll(g);
// Events are used instead of the following 2 lines...
//textBoxIncrease.Enabled = (sc.LargestArea > ShapeContainer.MAX_AREA) ? false : true;
//textBoxDecrease.Enabled = (sc.SmallestArea < ShapeContainer.MIN_AREA) ? false : true;
groupBoxViewOptions.Focus();
}
private void textBoxIncrease_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
// 1. Prevent the 'Ding' sound
e.Handled = true;
e.SuppressKeyPress = true;
// 2. Call Resize
PercentChange(textBoxIncrease);
}
clickEvent = 0;
}
private void textBoxDecrease_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
// 1. Prevent the 'Ding' sound
e.Handled = true;
e.SuppressKeyPress = true;
// 2. Call Resize
PercentChange(textBoxDecrease);
}
clickEvent = 0;
}
private void PercentChange(TextBox box)
{
// Go over List and resize all accordingly
int maxVal = box.Equals(textBoxDecrease) ? 99 : 500;
int percent;
if (int.TryParse(box.Text, out percent) && (percent >= 1) && (percent <= maxVal))
{
labelInvalidPercent1.Visible = false;
labelInvalidPercent2.Visible = false;
percent = box.Equals(textBoxDecrease) ? (percent * -1) : percent;
sc.ResizeAll(percent);
panel1.Refresh();
dirty = true;
}
else
{
if (box.Equals(textBoxDecrease))
labelInvalidPercent2.Visible = true;
else
labelInvalidPercent1.Visible = true;
SystemSounds.Beep.Play();
MessageBox.Show("Please enter a number between 1 - " + maxVal.ToString(), "Resize");
}
}
private void radioButtonViewByOrder_CheckedChanged(object sender, EventArgs e)
{
if (radioButtonViewByOrder.Checked == true)
{
// Sort Shapes Container (largest on bottom, smallest on top) and Redraw !
sc.Sort(new SortInputOrder());
panel1.Refresh();
}
clickEvent = 0;
}
private void radioButtonViewSmallestOnTop_CheckedChanged(object sender, EventArgs e)
{
if (radioButtonViewSmallestOnTop.Checked == true)
{
// Sort Shapes Container (largest on bottom, smallest on top) and Redraw !
sc.Sort(new SortLargeToSmall());
panel1.Refresh();
}
clickEvent = 0;
}
private void radioButtonViewLargestOnTop_CheckedChanged(object sender, EventArgs e)
{
if (radioButtonViewLargestOnTop.Checked == true)
{
// Sort Shapes Container (smallest on bottom, largest on top) and Redraw !
sc.Sort();
panel1.Refresh();
}
clickEvent = 0;
}
private void statusBarToolStripMenuItem_Click(object sender, EventArgs e)
{
// toggle status bar on / off
statusStrip1.Visible = !statusStrip1.Visible;
this.statusBarToolStripMenuItem.Image = statusStrip1.Visible ?
ShapesGraphics.Properties.Resources.GreenCheck : null;
clickEvent = 0;
}
private void gridLinesToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.gridLinesToolStripMenuItem.Image == null)
{
this.gridLinesToolStripMenuItem.Image = ShapesGraphics.Properties.Resources.GreenCheck;
DrawGrid(Color.LightGray);
}
else
{
this.gridLinesToolStripMenuItem.Image = null;
DrawGrid(panel1.BackColor);
}
panel1.Refresh();
}
private void DrawGrid(Color color)
{
int thick = 1;
int i = 0;
while (i < panel1.Size.Height)
{
// Draw horizontal lines
DrawLine(color, thick, 1, i, panel1.Size.Width, i);
i += 20;
}
i = 0;
while (i < panel1.Size.Width)
{
// Draw vertical lines
DrawLine(color, thick, i, 1, i, panel1.Size.Height);
i += 20;
}
}
private void DrawLine(Color color, int thick, int x1, int y1, int x2, int y2)
{
Graphics g;
using (g = panel1.CreateGraphics())
using (Pen pen = new Pen(color, thick))
{
g.DrawLine(pen, x1, y1, x2, y2);
}
}
private void SetPenBrushImage(int w, int h)
{
pen = new Pen(currentColor, int.Parse(comboBoxPenWidth.Text));
brush = new SolidBrush(currentColor);
image = null;
if (checkBoxFillShape.Checked)
{
// Brush type
if (radioButtonHatchFill.Checked)
{
brush = new HatchBrush(RandomEnumValue<HatchStyle>(), pictureBoxColor1.BackColor, pictureBoxColor2.BackColor);
}
if (radioButtonGradient.Checked)
{
System.Drawing.RectangleF r = new System.Drawing.Rectangle(0, 0, new Random().Next(1, w+1), new Random().Next(1, h+1));
LinearGradientMode lgm = RandomEnumValue<LinearGradientMode>();
//LinearGradientMode lgm = LinearGradientMode.Vertical;
brush = new LinearGradientBrush(r, pictureBoxColor1.BackColor, pictureBoxColor2.BackColor, lgm);
}
if (radioButtonImage.Checked)
{
try
{
if (string.IsNullOrEmpty(imageFileName))
{
labelRed.Visible = true;
throw new ShapesException("Image file not chosen, Please choose an image file");
}
else
image = new Bitmap(imageFileName);
}
catch (Exception e)
{
MessageBox.Show(e.Message,"Error");
throw e;
}
}
}
else
{
// Pen type
pen.DashStyle = DashStyle.Solid;
if (radioButtonDottedLine.Checked) pen.DashStyle = DashStyle.Dot;
if (radioButtonDashDot.Checked) pen.DashStyle = DashStyle.DashDot;
if (radioButtonDashDotDot.Checked) pen.DashStyle = DashStyle.DashDotDot;
}
}
private T RandomEnumValue<T>()
{
Array arr = Enum.GetValues(typeof(T));
return (T)arr.GetValue(new Random().Next(arr.Length));
}
private void comboBoxViewAll_KeyPress(object sender, KeyPressEventArgs e)
{
// to prevent user input
e.Handled = true;
}
private void comboBoxPenWidth_KeyPress(object sender, KeyPressEventArgs e)
{
// to prevent user input
e.Handled = true;
}
private void checkBoxFillShape_CheckStateChanged(object sender, EventArgs e)
{
groupBoxChooseBrush.Visible = (checkBoxFillShape.Checked == true) ? true : false;
groupBoxChoosePen.Visible = (checkBoxFillShape.Checked == true) ? false : true;
clickEvent = 0;
}
private void radioButtonSolidFill_CheckedChanged(object sender, EventArgs e)
{
groupBoxSet2Colors.Visible = false;
buttonImageBrowse.Visible = false;
labelRed.Visible = false;
clickEvent = 0;
}
private void radioButtonHatchFill_CheckedChanged(object sender, EventArgs e)
{
groupBoxSet2Colors.Visible = true;
buttonImageBrowse.Visible = false;
labelRed.Visible = false;
clickEvent = 0;
}
private void radioButtonGradient_CheckedChanged(object sender, EventArgs e)
{
groupBoxSet2Colors.Visible = true;
buttonImageBrowse.Visible = false;
labelRed.Visible = false;
clickEvent = 0;
}
private void radioButtonImage_CheckedChanged(object sender, EventArgs e)
{
groupBoxSet2Colors.Visible = false;
buttonImageBrowse.Visible = true;
buttonImageBrowse.Enabled = true;
clickEvent = 0;
}
private void groupBoxSet2Colors_VisibleChanged(object sender, EventArgs e)
{
if (groupBoxSet2Colors.Visible)
pictureBoxColor1.BackColor = currentColor;
}
private void pictureBoxColor1_Click(object sender, EventArgs e)
{
// Open color dialog
if (colorDialog1.ShowDialog() == DialogResult.OK)
{
pictureBoxColor1.BackColor = pictureBoxCurrentColor.BackColor = currentColor = colorDialog1.Color;
}
clickEvent = 0;
}
private void pictureBoxColor2_Click(object sender, EventArgs e)
{
// Open color dialog
if (colorDialog1.ShowDialog() == DialogResult.OK)
{
pictureBoxColor2.BackColor = colorDialog1.Color;
}
clickEvent = 0;
}
private void buttonImageBrowse_Click(object sender, EventArgs e)
{
// Open file dialog to choose image
openFileDialog1.Filter = "Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
imageFileName = openFileDialog1.FileName;
labelRed.Visible = false;
}
}
private void SetStatusBarView(bool a, bool b)
{
statusStrip1.Items[0].Visible = a;
statusStrip1.Items[1].Visible = a;
statusStrip1.Items[2].Visible = b;
statusStrip1.Items[3].Visible = b;
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (dirty)
{
bool needToSave = true;
if (string.IsNullOrEmpty(saveFileName))
{
// Open file dialog
saveFileDialog1.Title = "Save File: ";
saveFileDialog1.Filter = "dat files|*.dat";
saveFileDialog1.FileName = "";
needToSave = OpenTheSaveDialog();
}
if (needToSave)
{
try
{
SaveToFile();
dirty = false;
}
catch(IOException ex)
{
MessageBox.Show("Error Occured :: " + ex.Message, "Error");
}
}
}
}
private bool OpenTheSaveDialog()
{
bool needToSave = true;
DialogResult result = saveFileDialog1.ShowDialog();
if ((result == DialogResult.OK) && (saveFileDialog1.FileName != ""))
{
if (Path.GetExtension(saveFileDialog1.FileName).Equals(".dat"))
{
saveFileName = saveFileDialog1.FileName;
this.Text = APP_NAME + saveFileName;
}
else
{
// Trying to save with wrong file type
MessageBox.Show("File type must be *.dat","Note");
needToSave = false;
}
}
else // If cancel for example was pressed...
needToSave = false;
return needToSave;
}
private void SaveToFile()
{
try
{
// Create file, write (serialize) & close
BinaryFormatter binFormatter = new BinaryFormatter();
using (Stream fStream = new FileStream(saveFileName, FileMode.Create, FileAccess.Write, FileShare.None))
{
binFormatter.Serialize(fStream, sc);
}
// Update form title
this.Text = APP_NAME + saveFileName;
}
catch (SerializationException ex)
{
MessageBox.Show("Serialization Error :: " + ex.Message, "Error");
}
catch (Exception ex)
{
MessageBox.Show("Error Occured :: " + ex.Message, "Error");
}
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
DialogResult askResult = DialogResult.No;
// 1. If 'dirty' ....save first
if (dirty)
{
askResult = AskIfToSave(sender, e);
}
if (askResult == DialogResult.No)
{
// 2. Open existing file
openFileDialog1.Filter = "dat files|*.dat";
openFileDialog1.FileName = "";
DialogResult result = openFileDialog1.ShowDialog();
if ((result == DialogResult.OK) && (openFileDialog1.FileName != ""))
{
bool success = false;
string fName = openFileDialog1.FileName;
this.Text = APP_NAME + saveFileName;
clickEvent = 0;
ShapeContainer tempContainer = sc;
try
{
// 3. Read data from file to container
BinaryFormatter binFormatter = new BinaryFormatter();
using (Stream fStream = new FileStream(fName, FileMode.Open, FileAccess.Read, FileShare.None))
{
tempContainer = (ShapeContainer)binFormatter.Deserialize(fStream);
success = true;
}
}
catch (SerializationException)
{
MessageBox.Show("De-Serializaion Error Occured :: Invalid File Format", "Error");
}
catch (Exception ex)
{
MessageBox.Show("Error Occured :: " + ex.Message, "Error");
}
if (success)
{
// 4. Now we have the container
// Note:
// If error occured and file was not de-serialized than sc gets original data that was saved in the temp var
sc = tempContainer;
// 5. Resubscribe to class events !
SubscribeToAreaEvents();
// 6. Set view settings
this.Text = saveFileName = fName;
SetDevaultOrderView();
comboBoxViewAll.Text = ALL_SHAPES;
panel1.Refresh();
dirty = false;
}
}
}
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
// 1. If 'dirty' ....save first
if (dirty)
AskIfToSave(sender, e);
// 2. Clear all data
saveFileName = "";
this.Text = APP_NAME;
sc.RemoveAll();
clickEvent = 0;
panel1.Refresh();
dirty = false;
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
saveFileDialog1.Title = "Save File As: ";
saveFileDialog1.Filter = "dat files|*.dat";
saveFileDialog1.FileName = "";
if (OpenTheSaveDialog())
{
try
{
SaveToFile();
dirty = false;
}
catch (IOException ex)
{
MessageBox.Show("Error Occured :: " + ex.Message, "Error");
}
}
}
private DialogResult AskIfToSave(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("There are unsaved shapes." +
Environment.NewLine + "Do you want to save first ?", "Note",
MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
saveToolStripMenuItem_Click(sender, e);
}
return result;
}
private void saveFileAsImageToolStripMenuItem_Click(object sender, EventArgs e)
{