WPF拇指拖动和移动WindowState.Maximized
本文关键字:移动 WindowState Maximized 拖动 WPF | 更新日期: 2023-09-27 17:50:05
我有一个自定义窗口,WindowState=WindowState.Maximized
的边界和拇指在边界内,似乎当WindowState=WindowState.Maximized
我不能拖动和移动自定义窗口到不同的屏幕。
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Height="350"
Width="525"
WindowStyle="None">
<Border Name="headerBorder"
Width="Auto"
Height="50"
VerticalAlignment="Top"
CornerRadius="5,5,0,0"
DockPanel.Dock="Top"
Background="Red"
BorderThickness="1,1,1,1"
BorderBrush="Yellow">
<Grid x:Name="PART_Title">
<Thumb x:Name="headerThumb"
Opacity="0"
Background="{x:Null}"
Foreground="{x:Null}"
DragDelta="headerThumb_DragDelta"/>
</Grid>
</Border>
</Window>
c#: public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
WindowState = System.Windows.WindowState.Maximized;
}
private void headerThumb_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
{
Left = Left + e.HorizontalChange;
Top = Top + e.VerticalChange;
}
}
我也重写了MouseLeftButtonDown
方法并在里面使用DragMove()
,但没有成功。我也试着订阅拇指的MouseLeftButtonDown
,并在那里写DragMove()
,但没有成功。
默认情况下,最大化窗口不能移动,因此Left
和Top
没有作用。一种选择是注册到Thumb.DragStarted
事件并检查窗口是否被最大化。如果是,可以设置WindowState.Normal
,然后依次更新Left
和Top
属性。
private void Thumb_OnDragStarted(object sender, DragStartedEventArgs e)
{
// If the window is not maximized, do nothing
if (WindowState != WindowState.Maximized)
return;
// Set window state to normal
WindowState = WindowState.Normal;
// Here you have to determine the initial Left and Top values
// for the window that has WindowState normal
// I would use something like the native 'GetCursorPos' (in user32.dll)
// function to get the absolute mouse point on all screens
var point = new Win32Point();
GetCursorPos(ref point);
Left = point - certainXValue;
Top = point - certainYValue;
}
您可以在这里了解更多关于GetCursorPos
的信息。
然而,我强烈建议你使用。net 4.5附带的WindowChrome类,Max在评论中也建议了这一点。你只需要使用下面的代码,你就有了你想要的功能:
<Window x:Class="ThumbMaximizedWindow.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350"
Width="525"
WindowStyle="None"
WindowState="Maximized">
<WindowChrome.WindowChrome>
<WindowChrome />
</WindowChrome.WindowChrome>
</Window>