WPF中透明窗口实现拖拽功能

前言

默认创建的窗口是可以拖拽放大缩小的,但是如果窗口设置为透明,就不能拖拽了。

页面

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
<Grid Name="ImgGrid" Margin="0,0,0,0">
<Border
Margin="5"
Background="#333333"
BorderBrush="#2D8CF0"
BorderThickness="1">
<Image
Name="MImg"
MouseLeftButtonDown="Window_MouseLeftButtonDown_1"
Source="/Images/TouPing/phone_bg.jpg" />
</Border>

<Grid Name="MThumpGrid">
<Thumb
Width="16"
Height="16"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Cursor="ScrollNW"
DragDelta="LeftTop_DragDelta" />

<Thumb
Width="16"
Height="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Cursor="ScrollNE"
DragDelta="RightTop_DragDelta" />

<Thumb
Width="16"
Height="16"
HorizontalAlignment="Left"
VerticalAlignment="Bottom"
Cursor="ScrollSW"
DragDelta="LeftBottom_DragDelta" />

<Thumb
Width="16"
Height="16"
HorizontalAlignment="Right"
VerticalAlignment="Bottom"
Cursor="ScrollSE"
DragDelta="RightBottom_DragDelta" />
</Grid>
</Grid>

样式调整

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<Window.Resources>
<Style TargetType="Thumb">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Ellipse
Fill="White"
Stroke="#2D8CF0"
StrokeThickness="2" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>

事件

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
private void LeftTop_DragDelta(object sender, DragDeltaEventArgs e)
{
if (Width <= 400 && e.HorizontalChange > 0)
{
return;
}
if (Height <= 400 && e.VerticalChange > 0)
{
return;
}
Left += e.HorizontalChange;
Top += e.VerticalChange;
Width -= e.HorizontalChange;
Height -= e.VerticalChange;
}

private void LeftBottom_DragDelta(object sender, DragDeltaEventArgs e)
{
if (Width <= 400 && e.HorizontalChange > 0)
{
return;
}
if (Height <= 400 && e.VerticalChange < 0)
{
return;
}
Left += e.HorizontalChange;
Width -= e.HorizontalChange;
Height += e.VerticalChange;
}

private void RightTop_DragDelta(object sender, DragDeltaEventArgs e)
{
if (Width <= 400 && e.HorizontalChange < 0)
{
return;
}
if (Height <= 400 && e.VerticalChange > 0)
{
return;
}
Top += e.VerticalChange;
Width += e.HorizontalChange;
Height -= e.VerticalChange;
}

private void RightBottom_DragDelta(object sender, DragDeltaEventArgs e)
{
if (Width <= 400 && e.HorizontalChange < 0)
{
return;
}
if (Height <= 400 && e.VerticalChange < 0)
{
return;
}
Width += e.HorizontalChange;
Height += e.VerticalChange;
}