1
public class Test
2
{
3
private bool drawing;
4
private Point beginPoint;
5
private Point endPoint;
6
private Size size = new Size();
7
8
public Test()
9
{
10
InitializeComponent();
11
}
12
13
protected override void OnPaint(PaintEventArgs e)
14
{
15
if (drawing)
16
{
17
size.Width = endPoint.X - beginPoint.X;
18
size.Height = endPoint.Y - beginPoint.Y;
19
20
if (size.Width >= 0 && size.Height >= 0)
21
{
22
e.Graphics.DrawRectangle(Pens.Red, new Rectangle(beginPoint, size));
23
}
24
else
25
{
26
if (size.Width <= 0 && size.Height <= 0)
27
{
28
size.Width = Math.Abs(size.Width);
29
size.Height = Math.Abs(size.Height);
30
e.Graphics.DrawRectangle(Pens.Red, new Rectangle(endPoint, size));
31
}
32
else
33
{
34
if (size.Width > 0)
35
{
36
size.Width = Math.Abs(size.Width);
37
size.Height = Math.Abs(size.Height);
38
int x = beginPoint.X;
39
int y = endPoint.Y;
40
Point p = new Point(x, y);
41
42
e.Graphics.DrawRectangle(Pens.Red, new Rectangle(p, size));
43
}
44
else
45
{
46
size.Width = Math.Abs(size.Width);
47
size.Height = Math.Abs(size.Height);
48
int x = endPoint.X;
49
int y = beginPoint.Y;
50
Point p = new Point(x, y);
51
52
e.Graphics.DrawRectangle(Pens.Red, new Rectangle(p, size));
53
}
54
}
55
}
56
57
}
58
base.OnPaint(e);
59
}
60
61
private void Test_MouseMove(object sender, MouseEventArgs e)
62
{
63
if (drawing)
64
{
65
endPoint = e.Location;
66
Invalidate();
67
}
68
}
69
70
private void Test_MouseUp(object sender, MouseEventArgs e)
71
{
72
drawing = false;
73
endPoint = e.Location;
74
}
75
76
private void Test_MouseDown(object sender, MouseEventArgs e)
77
{
78
drawing = true;
79
beginPoint = e.Location;
80
}
81
82
}

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
