WPF实现程序窗体自定义拖拽
WPF如何实现自定义拖拽
WPF类似于WEB页面布局的优点是winForm无法具备的,通过它灵活的布局,样式的添加,可以制作出很炫的界面 ;
WPF怎么美化?WPF默认的窗口标题栏对于一些设计来说十分不合时宜,所以一般都会去掉替换上自有的设计,去掉标题栏的方法很多也分简单。不过,这样一来又会有另外一个问题,即去掉了标题栏后,没有了原有的拖拽和按住缩放大小的功能。 然而这两个功能大多数时候都是刚需,所以只能使用其他方式为自己替换的标题栏添加上这两个功能。
首先给模拟的标题栏添加 鼠标移动 和 鼠标点击 这两个事件
MouseMove="ResizePressed"
MouseDown="ResizePressed"
后台添加以下代码
#region 初始化窗体可以缩放大小
private const int WM_SYSCOMMAND = 0x112;
private HwndSource _HwndSource;
private Dictionary<ResizeDirection, Cursor> cursors = new Dictionary<ResizeDirection, Cursor>
{
{ ResizeDirection.BottomRight, Cursors.SizeNWSE },
};
private enum ResizeDirection
{
BottomRight = 8,
}
[DllImport( "user32.dll", CharSet = CharSet.Auto )]
private static extern IntPtr SendMessage( IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam );
private void ResizePressed( object sender, MouseEventArgs e )
{
FrameworkElement element = sender as FrameworkElement;
ResizeDirection direction = (ResizeDirection) Enum.Parse(typeof(ResizeDirection), element.Name.Replace( "Resize", "" ));
ResizeBottomRight.Cursor = cursors[direction];
if (e.LeftButton == MouseButtonState.Pressed)
ResizeWindow(direction);
}
private void ResizeWindow( ResizeDirection direction )
{
SendMessage( _HwndSource.Handle, WM_SYSCOMMAND, (IntPtr) (61440 + direction), IntPtr.Zero );
}
#endregion