2015-07-11 15:24:04 1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Text;
7 using System.Windows.Forms;
8
9 namespace 窗口停靠
10 {
11 public partial class Form1 : Form
12 {
13 string location =
null;
14 int y;
15 int x;
16 public Form1()
17 {
18 InitializeComponent();
19 }
20
21
22
23
24 /// <summary>
25
26 /// 当窗体的位置改变时发生
27
28 /// </summary>
29
30 /// <param name="sender"></param>
31
32 /// <param name="e"></param>
33
34 private void Form1_LocationChanged(
object sender, EventArgs e)
35 {
36 y =
this.Location.Y;
37 x =
this.Location.X;
38 if (
this.Top <=
0)
39 {
40
41 location =
"top";
42
43 }
44
45 else if (
this.Left <=
0)
46 {
47
48 location =
"left";
49
50 }
51
52
53 else if (
this.Right >=
Screen.PrimaryScreen.Bounds.Width)
54 {
55
56 location =
"right";
57
58 }
59 else
60 {
61 location =
"center";
62 }
63
64 }
65 private void timer2_Tick(
object sender, EventArgs e)
66 {
67
68 //如果鼠标在窗体上,则根据停靠位置显示整个窗体
69
70 if (
this.Bounds.Contains(Cursor.Position))
71 {
72
73 switch (location)
74 {
75
76 case "top":
77 if(
this.Location.Y<
0)
78 {
79 y +=
25;
80 if(y>
0)
81 {
82 y =
0;
83 }
84 this.Location =
new Point(
this.Location.X, y);
85 }
86 break;
87
88 case "left":
89
90 if(
this.Location.X<
0)
91 {
92 x +=
25;
93 if(x>
0)
94 {
95 x =
0;
96 }
97 this.Location =
new Point(x,
this.Location.Y);
98 }
99 break;
100
101 case "right":
102 if (
this.Location.X > Screen.PrimaryScreen.Bounds.Width -
this.Width)
103 {
104 x -=
25;
105 if (x < Screen.PrimaryScreen.Bounds.Width -
this.Width)
106 {
107 x = Screen.PrimaryScreen.Bounds.Width -
this.Width;
108 }
109 this.Location =
new Point(x,
this.Location.Y);
110 }
111 break;
112
113
114 }
115
116 }
117
118 else //如果鼠标离开窗体,则根据停靠位置隐藏窗体,但须留出部分窗体边缘以便鼠标选中窗体
119 {
120
121 switch (location)
122 {
123
124 case "top":
125
126 y = y -
25;
127 if(y>-
this.Height+
8)
128 {
129 this.Location =
new Point(
this.Location.X, y);
130
131 }
132 else
133 {
134 this.Location =
new Point(
this.Location.X, -
this.Height +
8);
135 }
136 break;
137
138
139 case "left":
140 x -=
25;
141 if(x>-
this.Width+
8)
142 {
143 this.Location =
new Point(x,
this.Location.Y);
144
145 }
146 else
147 {
148 this.Location =
new Point(-
this.Width +
8,
this.Location.Y);
149 }
150 break;
151
152 case "right":
153
154
155 if(x<Screen.PrimaryScreen.Bounds.Width-
8 )
156 {
157 x +=
25;
158 this.Location =
new Point(x,
this.Location.Y);
159
160 }
161 else
162 {
163 this.Location =
new Point(Screen.PrimaryScreen.Bounds.Width + -
8,
this.Location.Y);
164 }
165 break;
166 }
167
168 }
169
170 }
171 }
172
173 }
174
转载请注明原文地址: https://ju.6miu.com/read-17865.html